package com.jwsoft.manager.core.integration.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.servlet.ServletUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.bifang.assistant.common.vo.BaseVO;
import com.bifang.assistant.common.vo.OrderVO;
import com.bifang.engine.assistant.core.annotation.ApiService;
import com.bifang.engine.assistant.core.annotation.OpApi;
import com.bifang.engine.assistant.core.annotation.SaveOplog;
import com.bifang.engine.assistant.core.enums.AuTypeEnum;
import com.bifang.engine.assistant.core.enums.AuthStatusEnum;
import com.bifang.engine.assistant.core.enums.BoolEnum;
import com.bifang.engine.assistant.core.enums.FuncTypeEnum;
import com.bifang.engine.assistant.core.exception.AppException;
import com.bifang.engine.assistant.core.utils.SessionUtil;
import com.bifang.engine.cache.redis.RedisHelper;
import com.bifang.engine.data.core.util.PagerUtil;
import com.bifang.engine.protect.core.annotation.NoSignCrypto;
import com.bifang.module.base.common.util.ApplicationContextHelper;
import com.bifang.module.base.common.util.CommonSecureUtil;
import com.bifang.module.base.common.util.DesensitizeUtil;
import com.bifang.module.base.common.vo.common.CommonVO;
import com.bifang.module.base.common.vo.dict.DictAreaVO;
import com.bifang.module.base.common.vo.dict.SelectVO;
import com.bifang.module.base.common.vo.excel.ExcelModelVO;
import com.bifang.module.base.common.vo.excel.ExcelVO;
import com.bifang.module.base.core.helper.ApiContainer;
import com.bifang.module.base.core.helper.ApiModel;
import com.bifang.module.base.core.helper.DictHelper;
import com.bifang.module.base.core.helper.ExcelCommonHelper;
import com.bifang.module.base.core.integration.CommonIntegration;
import com.bifang.module.base.core.integration.DictIntegration;
import com.bifang.module.base.core.integration.ExcelIntegration;
import com.bifang.module.system.core.dao.model.PersonInfo;
import com.bifang.module.system.core.dao.model.SysUser;
import com.bifang.module.system.core.dao.service.PersonInfoService;
import com.bifang.module.system.core.dao.service.SysUserService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jwsoft.manager.common.constant.EduCache;
import com.jwsoft.manager.common.enums.*;
import com.jwsoft.manager.common.vo.YwApply.CompanyVO;
import com.jwsoft.manager.common.vo.YwApply.EnrollCheckShLqVO;
import com.jwsoft.manager.common.vo.YwApply.LivePlaceVO;
import com.jwsoft.manager.common.vo.YwApply.StudentStatusVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheDetailVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheQueryVO;
import com.jwsoft.manager.common.vo.cache.EduOperationCacheVO;
import com.jwsoft.manager.common.vo.eduDyjyQuerySync.EduDyjyQuerySyncVO;
import com.jwsoft.manager.common.vo.eduFormEnrollParams.EduFormEnrollParamsVO;
import com.jwsoft.manager.common.vo.eduFormSpecial.EduFormSpecialQueryVO;
import com.jwsoft.manager.common.vo.eduFormSpecial.EduFormSpecialVO;
import com.jwsoft.manager.common.vo.eduHouse.EduHouseVO;
import com.jwsoft.manager.common.vo.eduHousehold.EduHouseholdVO;
import com.jwsoft.manager.common.vo.eduJhjyQuerySync.EduJhjyQuerySyncVO;
import com.jwsoft.manager.common.vo.eduLivePlace.EduLivePlaceVO;
import com.jwsoft.manager.common.vo.eduNetsign.EduNetsignVO;
import com.jwsoft.manager.common.vo.eduPrivateAppointStudent.EduPrivateAppointStudentVO;
import com.jwsoft.manager.common.vo.eduSchool.EduSchoolVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.FormAppQueryVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.SchoolConfigQueryVO;
import com.jwsoft.manager.common.vo.eduSchoolConfig.SchoolConfigVO;
import com.jwsoft.manager.common.vo.eduSocialSecurity.EduSocialSecurityVO;
import com.jwsoft.manager.common.vo.eduStudentEnroll.*;
import com.jwsoft.manager.common.vo.eduStudentEnrollBefore.EduStudentEnrollBeforeVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollPre.EduStudentEnrollPreKeyVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollPre.EduStudentEnrollPreVO;
import com.jwsoft.manager.common.vo.eduStudentEnrollVerification.EduStudentEnrollVerificationVO;
import com.jwsoft.manager.common.vo.eduStudentTj.EduStudentTjVO;
import com.jwsoft.manager.common.vo.eduSystemConfig.EduSystemConfigFuncQueryVO;
import com.jwsoft.manager.core.dao.model.*;
import com.jwsoft.manager.core.dao.service.*;
import com.jwsoft.manager.core.integration.*;
import com.jwsoft.manager.core.util.EduDesensitizeUtil;
import com.jwsoft.manager.core.util.EduEnrollClearCacheHelper;
import com.jwsoft.manager.core.util.EduHelper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 学生注册表业务实现类
 *
 * @author wangtao
 * @since 2022-12-05
 */
@ApiService(funcCode = "eduStudentEnroll", title = "学生正式报名管理")
@Slf4j
public class EduStudentEnrollIntegrationImpl implements EduStudentEnrollIntegration {

    @Autowired
    public EduStudentEnrollService eduStudentEnrollService;
    @Autowired
    private OperationCacheIntegration operationCacheIntegration;
    @Autowired
    private EduStudentEnrollPreService eduStudentEnrollPreService;
    @Autowired
    private EduSystemConfigIntegration eduSystemConfigIntegration;
    @Autowired
    private EduStudentEnrollKindergartenService eduStudentEnrollKindergartenService;
    @Autowired
    private DictHelper dictHelper;
    @Autowired
    private EduSchoolTjService eduSchoolTjService;
    @Autowired
    private ApiContainer apiContainer;
    @Autowired
    private EduStudentEnrollBeforeService eduStudentEnrollBeforeService;
    @Autowired
    private EduHelper eduHelper;
    @Autowired
    private EduEnrollmenBrochureService eduEnrollmenBrochureService;
    @Autowired
    private EduSchoolService eduSchoolService;
    @Autowired
    private EduSchoolConfigService eduSchoolConfigService;
    @Autowired
    private ExcelIntegration excelIntegration;
    @Value("${spring.servlet.multipart.location}")
    private String tempPath;

    @Autowired
    private ExcelCommonHelper excelCommonHelper;

    @Autowired
    private RedisHelper redisHelper;
    @Autowired
    private EduStudentEnrollBeforeIntegration eduStudentEnrollBeforeIntegration;

    @Autowired
    private EduAreaService eduAreaService;
    @Autowired
    private EduStudentEnrollInvalidService eduStudentEnrollInvalidService;

    @Autowired
    private EduAuthSchoolService eduAuthSchoolService;

    @Autowired
    private EduHouseholdService eduHouseholdService;

    @Autowired
    private EduFormSpecialParamsService eduFormSpecialParamsService;

    @Autowired
    private EduNetsignService eduNetsignService;

    @Autowired
    private EduSocialSecurityService eduSocialSecurityService;

    @Autowired
    private EduCompanyService eduCompanyService;

    @Autowired
    private EduLivePlaceService eduLivePlaceService;

    @Autowired
    private EduStudentStatusService eduStudentStatusService;
    @Autowired
    public EduStudentEnrollFamilyService eduStudentEnrollFamilyService;
    @Autowired
    private EduHouseService eduHouseService;
    @Autowired
    private EduhHouseService eduhHouseService;

    @Autowired
    private EduStudentEnrollBlacklistService eduStudentEnrollBlacklistService;

    @Autowired
    private EduFormEnrollParamsService eduFormEnrollParamsService;

    @Autowired
    private CommonIntegration commonIntegration;

    @Autowired
    private EduJhjyQuerySyncIntegration eduJhjyQuerySyncIntegration;

    @Autowired
    private EduStudentTjService eduStudentTjService;
    @Autowired
    private EduStudentEnrollVerificationService eduStudentEnrollVerificationService;
    @Autowired
    private EduEnrollClearCacheHelper eduEnrollClearCacheHelper;

    @Autowired
    private EduAppointSchoolService eduAppointSchoolService;

    @Autowired
    private EduSchoolConfigIntegration eduSchoolConfigIntegration;

    @Autowired
    private EduFormEnrollService eduFormEnrollService;

    @Autowired
    private EduFormSpecialService eduFormSpecialService;

    @Autowired
    private PersonInfoService personInfoService;
    @Autowired
    private EduTalentPoolService eduTalentPoolService;


    public static final String REDIS_YHDR = "YWMBAPPLY:yhdr:";
    public static final String batchAdmitKey = "YWBATCHADMIT:";
    public static final String stopKey = "YWJSZS:";

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private EduSchoolLrService eduSchoolLrService;

    @Autowired
    private DictIntegration dictIntegration;

    @Autowired
    private EduDyjyQuerySyncIntegration dyjyQuerySyncIntegration;

    @Autowired
    private  EduDataTaskDetailService eduDataTaskDetailService;

    @Autowired
    public EduhStudentEnrollService eduhStudentEnrollService;

    @Autowired
    private EduhHouseholdService eduhHouseholdService;

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private static final String STUDENT_ENROLL_TABLE = "edu_student_enroll";
    private static final String EDU_HOUSEHOLD = "edu_household";
    @Override
    @OpApi(funcCode = "eduStudentEnroll0001", title = "学生正式报名管理分页查询-东阳模式", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduStudentEnrollVO> getList(EduStudentEnrollQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(20);
        }

        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }


        if (StringUtils.isBlank(vo.getOpType())) {
            vo.setOpType("9");
        }
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setYear(vo.getYear());
        checkShLqVO.setOpType(vo.getOpType());
        checkShLqVO.setSchoolId(vo.getSchoolId());
        checkShLqVO.setAreaCode(vo.getAreaCode());
        Boolean checkFlag = checkShLq(checkShLqVO);
        if (!checkFlag) {
            throw new AppException("本年度招生审核工作尚未开始");
        }

        if (!CollectionUtils.isEmpty(vo.getOrderVOList())) {
            String orderBy = "";
            for (OrderVO orderVO : vo.getOrderVOList()) {
                if (StringUtils.isNotBlank(orderVO.getOrder()) && StringUtils.isNotBlank(orderVO.getProperty())) {
                    orderBy = orderBy + ",";
                    if (orderVO.getProperty().equals("registerDate")) {
                        orderBy = orderBy + "a.";
                    } else if (orderVO.getProperty().equals("qysj")) {
                        orderBy = orderBy + "a.";
                    } else {
                        orderBy = orderBy + "a.";
                    }
                    orderBy = orderBy + StrUtil.toUnderlineCase(orderVO.getProperty()) + " " + orderVO.getOrder();
                }
            }
            vo.setOrderBy(orderBy);

        }

        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (!CollectionUtils.isEmpty(areaCodeList)){
            vo.setAreaCodeList(areaCodeList);
        }else{
            throw new AppException("必须传入行政区划");
        }
        PageInfo<EduStudentEnrollVO> pageInfo = new PageInfo<>();
        List<EduStudentEnrollVO> resultList = new ArrayList<>();
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),STUDENT_ENROLL_TABLE);
        if (!queryHistoryFlag) {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduStudentEnrollVO> list = eduStudentEnrollService.getYwApplyList(vo);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            pageInfo = new PageInfo<>(list);
            for (EduStudentEnrollVO enrollVO : list) {
                /*
                 * source:6 学校录入报名数据
                 * */
                if (StringUtils.isNotEmpty(enrollVO.getSource())) {
                    if ("6".equals(enrollVO.getSource())) {
                        enrollVO.setFileInfo(enrollVO.getParam20());
                    }
                }
            }
        } else {
            Boolean encryptFlag = eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), STUDENT_ENROLL_TABLE);
            if (encryptFlag) {
                eduStudentEnrollService.queryEncrypt(vo);
            }
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduStudentEnrollVO> list = eduhStudentEnrollService.getYwApplyListYq(vo);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            for (EduStudentEnrollVO enrollVO : list) {
                /*
                 * source:6 学校录入报名数据
                 * */
                if (StringUtils.isNotEmpty(enrollVO.getSource())) {
                    if ("6".equals(enrollVO.getSource())) {
                        enrollVO.setFileInfo(enrollVO.getParam20());
                    }
                }
            }
            // 不为空则获取分页结果
            pageInfo = new PageInfo<>(list);
        }

        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        resultList = pageInfo.getList();
        dictHelper.valueToName(resultList, Arrays.asList(EduYwEnrollDictEnum.values()));
        Map<String, EduArea> areaMap =
                eduAreaService.list().stream()
                        .collect(Collectors.toMap(EduArea::getAreaCode, a -> a, (k1, k2) -> k1));
        boolean flag = false;
        String cqSchool = "all";//commonIntegration.getValueByKey("cq_school");
        Map<String, EduStudentEnroll> map = new HashMap<>();
        Map<String, String> schoolMap = new HashMap<>();
        if (StringUtils.isNotBlank(cqSchool)) {
            // 获取公办报名学校和类别
            List<String> idList = resultList.stream().map(EduStudentEnrollVO::getParentId).collect(Collectors.toList());
            List<EduStudentEnroll> eduStudentEnrollList;
            if (!queryHistoryFlag){
                QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().select(EduStudentEnroll::getIdcard, EduStudentEnroll::getSchoolId, EduStudentEnroll::getConfigName)
                        .in(EduStudentEnroll::getStudentEnrollId, idList);
                if (!"all".equals(cqSchool)) {
                    List<String> schoolIdList = Arrays.stream(cqSchool.split(",")).map(s -> s).collect(Collectors.toList());
                    queryWrapper.lambda().in(EduStudentEnroll::getSchoolId, schoolIdList);
                }
                 eduStudentEnrollList = eduStudentEnrollService.list(queryWrapper);
            }else {
                QueryWrapper<EduhStudentEnroll> eduhStudentEnrollQueryWrapper = new QueryWrapper<>();
                eduhStudentEnrollQueryWrapper.lambda().select(EduhStudentEnroll::getIdcard, EduhStudentEnroll::getSchoolId, EduhStudentEnroll::getConfigName)
                        .in(EduhStudentEnroll::getStudentEnrollId, idList);
                if (!"all".equals(cqSchool)) {
                    List<String> schoolIdList = Arrays.stream(cqSchool.split(",")).map(s -> s).collect(Collectors.toList());
                    eduhStudentEnrollQueryWrapper.lambda().in(EduhStudentEnroll::getSchoolId, schoolIdList);
                }
                List<EduhStudentEnroll> eduhStudentEnrollList = eduhStudentEnrollService.list(eduhStudentEnrollQueryWrapper);

                eduStudentEnrollList = Convert.toList(EduStudentEnroll.class, eduhStudentEnrollList);
            }

            if (!CollectionUtils.isEmpty(eduStudentEnrollList)) {
                map = eduStudentEnrollList.stream().collect(Collectors.toMap(EduStudentEnroll::getIdcard, a -> a, (k1, k2) -> k1));
                List<String> orgIds = eduStudentEnrollList.stream().map(EduStudentEnroll::getSchoolId).collect(Collectors.toList());
                List<EduSchool> schoolList = eduSchoolService.listByIds(orgIds);
                if (!CollectionUtils.isEmpty(schoolList)) {
                    schoolMap = schoolList.stream().collect(Collectors.toMap(EduSchool::getOrgId, EduSchool::getShortName, (k1, k2) -> k1));
                }

            }
        }
        //获取报名id
        List<String> enrollIdList = resultList.stream().map(EduStudentEnrollVO::getStudentEnrollId).distinct().collect(Collectors.toList());
        List<String> authStatusList = new ArrayList<>();
        authStatusList.add(AuthStatusEnum.NODO.getType());
        authStatusList.add(AuthStatusEnum.YES.getType());
        QueryWrapper<EduStudentEnrollInvalid> invalidQueryWrapper = new QueryWrapper<>();
        invalidQueryWrapper.lambda()
                .select(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus)
                .in(EduStudentEnrollInvalid::getStudentEnrollId, enrollIdList)
                .in(EduStudentEnrollInvalid::getAuthStatus, authStatusList);
        List<EduStudentEnrollInvalid> invalidList = eduStudentEnrollInvalidService.list(invalidQueryWrapper);
        Map<String, String> collectMap =new HashMap<>();
        if(!CollectionUtils.isEmpty(invalidList)){
            collectMap=invalidList.stream().collect(Collectors.toMap(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus));
        }


        for (EduStudentEnrollVO studentEnroll : resultList) {
            if ("1".equals(studentEnroll.getEncryptFlag())){
                eduStudentEnrollService.decrypt(studentEnroll);
            }

            EduStudentEnroll enroll = map.get(studentEnroll.getIdcard());
            if (enroll != null) {
                studentEnroll.setGbConfigName(enroll.getConfigName());
                studentEnroll.setGbSchoolName(schoolMap.get(enroll.getSchoolId()));
            }

            studentEnroll.setDelStatus(collectMap.get(studentEnroll.getStudentEnrollId()));

            if (!flag && EnrollStatusFormalEnum.dlq.getType().equals(studentEnroll.getEnrollStatus())) {
                flag = true;
                studentEnroll.setFirstFlag(true);
            } else {
                studentEnroll.setFirstFlag(false);
            }
            //设置街道
            if (!ObjectUtils.isEmpty(areaMap.get(studentEnroll.getStreet()))) {
                studentEnroll.setStreetName(areaMap.get(studentEnroll.getStreet()).getAreaName());
            }
            if (StringUtils.isBlank(studentEnroll.getAdmitFlag())) {
                studentEnroll.setAdmitFlag("2");
                studentEnroll.setAdmitFlagName("待录取");
            } else {
                if (BoolEnum.TRUE.getType().equals(studentEnroll.getAdmitFlag())) {
                    studentEnroll.setAdmitFlagName("已录取");
                } else {
                    studentEnroll.setAdmitFlagName("不予录取");
                }
            }
            if (BoolEnum.TRUE.getType().equals(studentEnroll.getSpecialFlag())) {
                studentEnroll.setSpecialFlagName("是");
            } else {
                studentEnroll.setSpecialFlagName("否");
            }
            if (StringUtils.isNotBlank(studentEnroll.getEnrollStatus())) {
                EnrollStatusFormalEnum formalEnum = EnrollStatusFormalEnum.getByType(studentEnroll.getEnrollStatus());
                studentEnroll.setEnrollStatusName(formalEnum == null ? "未知状态" : formalEnum.getName());
            } else {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
                studentEnroll.setEnrollStatusName(EnrollStatusFormalEnum.dsh.getName());
            }
        }

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0065", title = "学生报名撤销分页查询-东阳模式", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public PageInfo<EduStudentEnrollVO> getQuashList(EduStudentEnrollQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(20);
        }

        if (ObjectUtils.isEmpty(vo.getYear())) {
            vo.setYear(eduHelper.thisYear());
        }


        if (StringUtils.isBlank(vo.getOpType())) {
            vo.setOpType("9");
        }
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setYear(vo.getYear());
        checkShLqVO.setOpType(vo.getOpType());
        checkShLqVO.setSchoolId(vo.getSchoolId());
        checkShLqVO.setAreaCode(vo.getAreaCode());
        Boolean checkFlag = checkShLq(checkShLqVO);
        if (!checkFlag) {
            throw new AppException("本年度招生审核工作尚未开始");
        }

        if (!CollectionUtils.isEmpty(vo.getOrderVOList())) {
            String orderBy = "";
            for (OrderVO orderVO : vo.getOrderVOList()) {
                if (StringUtils.isNotBlank(orderVO.getOrder()) && StringUtils.isNotBlank(orderVO.getProperty())) {
                    orderBy = orderBy + ",";
                    if (orderVO.getProperty().equals("registerDate")) {
                        orderBy = orderBy + "a.";
                    } else if (orderVO.getProperty().equals("qysj")) {
                        orderBy = orderBy + "a.";
                    } else {
                        orderBy = orderBy + "a.";
                    }
                    orderBy = orderBy + StrUtil.toUnderlineCase(orderVO.getProperty()) + " " + orderVO.getOrder();
                }
            }
            vo.setOrderBy(orderBy);

        }

        List<String> areaCodeList = new ArrayList<>();
        if (ObjectUtils.isEmpty(vo.getAreaCode())){
            List<SelectVO> selectVOList = dictIntegration.getDistrictByOrg(new DictAreaVO());
            areaCodeList = selectVOList.stream()
                    .map(SelectVO::getDictKey)
                    .collect(Collectors.toList());
            String sessionAreaCode = SessionUtil.getAreaCode();
            if (!areaCodeList.contains(sessionAreaCode)) {
                areaCodeList.add(sessionAreaCode);
            }
        }else {
            areaCodeList.add(vo.getAreaCode());
        }
        if (!CollectionUtils.isEmpty(areaCodeList)){
            vo.setAreaCodeList(areaCodeList);
        }else{
            throw new AppException("必须传入行政区划");
        }
        PageInfo<EduStudentEnrollVO> pageInfo = new PageInfo<>();
        List<EduStudentEnrollVO> resultList = new ArrayList<>();
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),STUDENT_ENROLL_TABLE);
        if (!queryHistoryFlag) {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduStudentEnrollVO> list = eduStudentEnrollService.getYwApplyListYqQuash(vo);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            // 不为空则获取分页结果
            pageInfo = new PageInfo<>(list);
            for (EduStudentEnrollVO enrollVO : list) {
                /*
                 * source:6 学校录入报名数据
                 * */
                if (StringUtils.isNotEmpty(enrollVO.getSource())) {
                    if ("6".equals(enrollVO.getSource())) {
                        enrollVO.setFileInfo(enrollVO.getParam20());
                    }
                }
            }
        } else {
            Boolean encryptFlag = eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), STUDENT_ENROLL_TABLE);
            if (encryptFlag) {
                eduStudentEnrollService.queryEncrypt(vo);
            }
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            List<EduStudentEnrollVO> list = eduhStudentEnrollService.getYwApplyListYqQuash(vo);
            if (CollectionUtils.isEmpty(list)) {
                // 判断是否为空，为空则返回空参数
                return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
            }
            for (EduStudentEnrollVO enrollVO : list) {
                /*
                 * source:6 学校录入报名数据
                 * */
                if (StringUtils.isNotEmpty(enrollVO.getSource())) {
                    if ("6".equals(enrollVO.getSource())) {
                        enrollVO.setFileInfo(enrollVO.getParam20());
                    }
                }
            }
            // 不为空则获取分页结果
            pageInfo = new PageInfo<>(list);
        }

        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        resultList = pageInfo.getList();
        dictHelper.valueToName(resultList, Arrays.asList(EduYwEnrollDictEnum.values()));
        Map<String, EduArea> areaMap =
                eduAreaService.list().stream()
                        .collect(Collectors.toMap(EduArea::getAreaCode, a -> a, (k1, k2) -> k1));
        boolean flag = false;
        String cqSchool = "all";//commonIntegration.getValueByKey("cq_school");
        Map<String, EduStudentEnroll> map = new HashMap<>();
        Map<String, String> schoolMap = new HashMap<>();
        if (StringUtils.isNotBlank(cqSchool)) {
            // 获取公办报名学校和类别
            List<String> idList = resultList.stream().map(EduStudentEnrollVO::getParentId).collect(Collectors.toList());
            List<EduStudentEnroll> eduStudentEnrollList;
            if (!queryHistoryFlag){
                QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().select(EduStudentEnroll::getIdcard, EduStudentEnroll::getSchoolId, EduStudentEnroll::getConfigName)
                        .in(EduStudentEnroll::getStudentEnrollId, idList);
                if (!"all".equals(cqSchool)) {
                    List<String> schoolIdList = Arrays.stream(cqSchool.split(",")).map(s -> s).collect(Collectors.toList());
                    queryWrapper.lambda().in(EduStudentEnroll::getSchoolId, schoolIdList);
                }
                eduStudentEnrollList = eduStudentEnrollService.list(queryWrapper);
            }else {
                QueryWrapper<EduhStudentEnroll> eduhStudentEnrollQueryWrapper = new QueryWrapper<>();
                eduhStudentEnrollQueryWrapper.lambda().select(EduhStudentEnroll::getIdcard, EduhStudentEnroll::getSchoolId, EduhStudentEnroll::getConfigName)
                        .in(EduhStudentEnroll::getStudentEnrollId, idList);
                if (!"all".equals(cqSchool)) {
                    List<String> schoolIdList = Arrays.stream(cqSchool.split(",")).map(s -> s).collect(Collectors.toList());
                    eduhStudentEnrollQueryWrapper.lambda().in(EduhStudentEnroll::getSchoolId, schoolIdList);
                }
                List<EduhStudentEnroll> eduhStudentEnrollList = eduhStudentEnrollService.list(eduhStudentEnrollQueryWrapper);

                eduStudentEnrollList = Convert.toList(EduStudentEnroll.class, eduhStudentEnrollList);
            }

            if (!CollectionUtils.isEmpty(eduStudentEnrollList)) {
                map = eduStudentEnrollList.stream().collect(Collectors.toMap(EduStudentEnroll::getIdcard, a -> a, (k1, k2) -> k1));
                List<String> orgIds = eduStudentEnrollList.stream().map(EduStudentEnroll::getSchoolId).collect(Collectors.toList());
                List<EduSchool> schoolList = eduSchoolService.listByIds(orgIds);
                if (!CollectionUtils.isEmpty(schoolList)) {
                    schoolMap = schoolList.stream().collect(Collectors.toMap(EduSchool::getOrgId, EduSchool::getShortName, (k1, k2) -> k1));
                }

            }
        }
        //获取报名id
        List<String> enrollIdList = resultList.stream().map(EduStudentEnrollVO::getStudentEnrollId).distinct().collect(Collectors.toList());
        List<String> authStatusList = new ArrayList<>();
        authStatusList.add(AuthStatusEnum.NODO.getType());
        authStatusList.add(AuthStatusEnum.YES.getType());
        QueryWrapper<EduStudentEnrollInvalid> invalidQueryWrapper = new QueryWrapper<>();
        invalidQueryWrapper.lambda()
                .select(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus)
                .in(EduStudentEnrollInvalid::getStudentEnrollId, enrollIdList)
                .in(EduStudentEnrollInvalid::getAuthStatus, authStatusList);
        List<EduStudentEnrollInvalid> invalidList = eduStudentEnrollInvalidService.list(invalidQueryWrapper);
        Map<String, String> collectMap =new HashMap<>();
        if(!CollectionUtils.isEmpty(invalidList)){
            collectMap=invalidList.stream().collect(Collectors.toMap(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus));
        }

        // 收集所有不重复的创建用户ID和修改用户ID
        List<String> userIdList = resultList.stream()
                .flatMap(enroll -> Stream.of(enroll.getCreateName(), enroll.getUpdateName()))
                .filter(Objects::nonNull)
                .distinct()
                .collect(Collectors.toList());
        Map<String, String> userMap = new HashMap<>();

        if (!CollectionUtils.isEmpty(userIdList)){
            QueryWrapper<SysUser> userQueryWrapper = new QueryWrapper<>();
            userQueryWrapper.lambda()
                    .in(SysUser::getUserId, userIdList);
            List<SysUser> userList = sysUserService.list(userQueryWrapper);
            userMap = userList.stream().collect(Collectors.toMap(SysUser::getUserId, SysUser::getFullName));
        }

        for (EduStudentEnrollVO studentEnroll : resultList) {
            if ("1".equals(studentEnroll.getEncryptFlag())){
                eduStudentEnrollService.decrypt(studentEnroll);
            }

            EduStudentEnroll enroll = map.get(studentEnroll.getIdcard());
            if (enroll != null) {
                studentEnroll.setGbConfigName(enroll.getConfigName());
                studentEnroll.setGbSchoolName(schoolMap.get(enroll.getSchoolId()));
            }

            studentEnroll.setDelStatus(collectMap.get(studentEnroll.getStudentEnrollId()));

            if (!flag && EnrollStatusFormalEnum.dlq.getType().equals(studentEnroll.getEnrollStatus())) {
                flag = true;
                studentEnroll.setFirstFlag(true);
            } else {
                studentEnroll.setFirstFlag(false);
            }
            //设置街道
            if (!ObjectUtils.isEmpty(areaMap.get(studentEnroll.getStreet()))) {
                studentEnroll.setStreetName(areaMap.get(studentEnroll.getStreet()).getAreaName());
            }
            if (StringUtils.isBlank(studentEnroll.getAdmitFlag())) {
                studentEnroll.setAdmitFlag("2");
                studentEnroll.setAdmitFlagName("待录取");
            } else {
                if (BoolEnum.TRUE.getType().equals(studentEnroll.getAdmitFlag())) {
                    studentEnroll.setAdmitFlagName("已录取");
                } else {
                    studentEnroll.setAdmitFlagName("不予录取");
                }
            }
            if (BoolEnum.TRUE.getType().equals(studentEnroll.getSpecialFlag())) {
                studentEnroll.setSpecialFlagName("是");
            } else {
                studentEnroll.setSpecialFlagName("否");
            }
            if (StringUtils.isNotBlank(studentEnroll.getEnrollStatus())) {
                EnrollStatusFormalEnum formalEnum = EnrollStatusFormalEnum.getByType(studentEnroll.getEnrollStatus());
                studentEnroll.setEnrollStatusName(formalEnum == null ? "未知状态" : formalEnum.getName());
            } else {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
                studentEnroll.setEnrollStatusName(EnrollStatusFormalEnum.dsh.getName());
            }

            String createUser = userMap.get(studentEnroll.getCreateName());
            if(createUser != null){
                studentEnroll.setCreateNameChinese(createUser);
            }
            String updateUser = userMap.get(studentEnroll.getUpdateName());
            if(updateUser != null){
                studentEnroll.setUpdateNameChinese(updateUser);
            }
        }

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0002", title = "学生正式报名管理根据主键查询详情", funcType = FuncTypeEnum.query)
    public EduStudentEnrollVO getById(EduStudentEnrollKeyVO vo) {
        EduStudentEnroll entity = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("查询不到详细信息!");
        }
        EduStudentEnrollVO result = Convert.convert(EduStudentEnrollVO.class, entity);
        QueryWrapper<EduStudentEnrollVerification> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnrollVerification::getStudentEnrollId,result.getStudentEnrollId());
        List<EduStudentEnrollVerification> list=eduStudentEnrollVerificationService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)){
            result.setVerificationVOList(Convert.toList(EduStudentEnrollVerificationVO.class,list));
        }else{
            result.setVerificationVOList(new ArrayList<>());
        }
        return result;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0023", title = "家长端查询可报名的人员信息", funcType = FuncTypeEnum.query)
    public List<BmStudentVO> getPreListByToken(BmQueryVO vo) {
        String idcard= SessionUtil.getSessionInfo()!=null?SessionUtil.getSessionInfo().getIdcard():null;
        if(StringUtils.isBlank(idcard)){
            throw new AppException("用户未登录或未获取到身份信息");
        }
        int year = eduHelper.thisYear();

        QueryWrapper<EduStudentEnrollPre> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnrollPre::getYear,year)
                .and(
                        wrapper -> {
                            wrapper.eq(EduStudentEnrollPre::getFatherIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getIdcard, idcard)
                                    .or()
                                    .eq(EduStudentEnrollPre::getMotherIdcard, idcard);
                        }).eq(EduStudentEnrollPre::getAuthStatus,AuthStatusEnum.YES.getType());
        if(StringUtils.isNotBlank(vo.getSchoolCategory())){
            queryWrapper.lambda().eq(EduStudentEnrollPre::getSchoolCategory,vo.getSchoolCategory());
        }
        List<EduStudentEnrollPre> list = eduStudentEnrollPreService.list(queryWrapper);
        List<BmStudentVO> retList=new ArrayList<>();
        boolean flag=true;
        if(!CollectionUtils.isEmpty(list)){
            Map<String,String> beforeMap=new HashMap<>();
            if(BoolEnum.TRUE.getType().equalsIgnoreCase(vo.getSpecialFlag())){
                List<String> preIdList=list.stream().map(EduStudentEnrollPre::getStudentEnrollPreId).distinct().collect(Collectors.toList());
                QueryWrapper<EduStudentEnrollBefore> beforeQueryWrapper=new QueryWrapper<>();
                beforeQueryWrapper.lambda().select(EduStudentEnrollBefore::getStudentEnrollPreId).eq(EduStudentEnrollBefore::getSpecialFlag,BoolEnum.TRUE.getType())
                        .in(EduStudentEnrollBefore::getStudentEnrollPreId,preIdList)
                        .eq(EduStudentEnrollBefore::getAuthStatus,AuthStatusEnum.YES.getType());
                List<EduStudentEnrollBefore> beforeList=eduStudentEnrollBeforeService.list(beforeQueryWrapper);
                if(!CollectionUtils.isEmpty(beforeList)){
                    beforeMap=beforeList.stream().collect(Collectors.toMap(EduStudentEnrollBefore::getStudentEnrollPreId, EduStudentEnrollBefore::getStudentEnrollPreId,(k1,k2)->k1));
                }
            }
            List<String> enrollStatusList=new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());

            for(EduStudentEnrollPre pre:list){
                QueryWrapper<EduStudentEnroll> enrollQueryWrapper =new QueryWrapper<>();
                enrollQueryWrapper.lambda().eq(EduStudentEnroll::getIdcard,pre.getIdcard())
                        .eq(EduStudentEnroll::getYear,pre.getYear())
                        .in(EduStudentEnroll::getEnrollStatus,enrollStatusList);
                if(eduStudentEnrollService.count(enrollQueryWrapper)<=0){
                    BmStudentVO studentEnrollPreVO=Convert.convert(BmStudentVO.class,pre);
                    QueryWrapper<EduStudentEnrollBefore> beforeQueryWrapper =new QueryWrapper<>();
                    beforeQueryWrapper.lambda().eq(EduStudentEnrollBefore::getStudentEnrollPreId,pre.getStudentEnrollPreId())
                            .eq(EduStudentEnrollBefore::getYear,pre.getYear())
                            .eq(EduStudentEnrollBefore::getAuthStatus,AuthStatusEnum.YES.getType());
                    if(eduStudentEnrollBeforeService.count(beforeQueryWrapper)<=0){
                        studentEnrollPreVO.setYjbmFlag(false);
                    }else{
                        studentEnrollPreVO.setYjbmFlag(true);
                    }
                    if(BoolEnum.TRUE.getType().equalsIgnoreCase(vo.getSpecialFlag())){
                        //只取特殊通道人员
                        if(beforeMap.containsKey(pre.getStudentEnrollPreId())){
                            retList.add(studentEnrollPreVO);
                        }
                    }else {
                        retList.add(studentEnrollPreVO);
                    }
                }else{
                    flag=false;
                }
            }
        }

        if(CollectionUtils.isEmpty(retList)){
            if(!flag){
                throw new AppException(2,"已报名，是否请前往我的报名查看报名结果？");
            }else{
                throw new AppException(3,"该学段在系统中未匹配到适龄子女，是否前往准新生登记办理登记？");
            }
        }

        return retList;

    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0028", title = "家长端查询可报名的人员信息详情", funcType = FuncTypeEnum.query)
    public EduStudentEnrollPreVO getBeforeByPreId(EduStudentEnrollPreKeyVO vo) {
        Integer year=eduHelper.thisYear();
        if (vo.getYear()==null){
            year=eduHelper.thisYear();
        }
        EduStudentEnrollPreVO enrollPreVO = eduStudentEnrollBeforeIntegration.getPreDetail(vo);
        EduStudentEnrollPreVO preVO = new EduStudentEnrollPreVO();
        BeanUtil.copyProperties(enrollPreVO, preVO);
        if(StringUtils.isBlank(preVO.getAreaCode())){
            preVO.setAreaCode(eduHelper.thisAreaCode());
        }
        if(StringUtils.isBlank(preVO.getFatherCardType())){
            preVO.setFatherCardType(CardTypeEnum.idcard.getType());
        }
        if(StringUtils.isBlank(preVO.getMotherCardType())){
            preVO.setMotherCardType(CardTypeEnum.idcard.getType());
        }
        if(StringUtils.isBlank(preVO.getCardType())){
            preVO.setCardType(CardTypeEnum.idcard.getType());
        }
        preVO.setSchoolId(null);

        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(preVO.getAreaCode());
        queryVO.setYear(year);
        EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
        if(eduOperationCacheVO==null){
            throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
        }
        Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();

        EduOperationCacheDetailVO bmOperation=operation.get("YW002");//报名时间
        EduOperationCacheDetailVO bbOperation=operation.get("YW022");//补报时间
        EduOperationCacheDetailVO qbOperation=operation.get("YW010");//抢报时间
        //判断是否报名业务期
        boolean bmFlag = bmOperation==null?false:bmOperation.isFlag();
        //判断是否补报业务期
        boolean bbFlag = bmFlag || bbOperation == null ? false : bbOperation.isFlag();
        //判断是否空额抢报业务期
        boolean qbFlag = bmFlag || qbOperation == null ? false : qbOperation.isFlag();

        CommonVO commonTestVO=new CommonVO();
        commonTestVO.setParamKey("imitate_flag");
        String mnFlagStr=commonIntegration.getValueByKey(commonTestVO);
        preVO.setMnFlag(false);
        if("1".equalsIgnoreCase(mnFlagStr)||"true".equalsIgnoreCase(mnFlagStr)){
            //开启模拟报名
            EduOperationCacheDetailVO mnOperation=operation.get("YW062");//模拟报名时间
            //判断是否模拟报名业务期
            boolean mnFlag = mnOperation==null?false:mnOperation.isFlag();
            if(!mnFlag&&!bmFlag&&!bbFlag&&!qbFlag){
                throw new AppException("未在有效报名时间内");
            }
            preVO.setMnFlag(mnFlag);
        }else{
            if(!bmFlag&&!bbFlag&&!qbFlag){
                throw new AppException("未在有效报名时间内");
            }
        }


        preVO.setEnrollFlag(bmFlag);
        preVO.setBbFlag(bbFlag);
        preVO.setQbFlag(qbFlag);
        preVO.setShowMbFlag(false);
        preVO.setShowMzgFlag(false);
        boolean canEnrollFlag=false;
        //处理户籍数据
        if(preVO.getHouseHoldVO()!=null){
            if ("330783".equals(preVO.getHouseHoldVO().getAreaCode())) {
                canEnrollFlag = true;
                //2025年度开放有户籍之外的可以报民办学校
                //preVO.setShowMbFlag(true);
                preVO.setShowMzgFlag(true);
                preVO.setHouseholdPlace(preVO.getHouseholdAddress());
            }
        }
        boolean cFlag=false;
        preVO.setGatFlag(false);
        if(!CollectionUtils.isEmpty(preVO.getEnrollBeforeList())){
            for(EduStudentEnrollBeforeVO beforeVO:preVO.getEnrollBeforeList()){
                if(BoolEnum.TRUE.getType().equalsIgnoreCase(beforeVO.getSpecialFlag())){
                    //特殊通道 判断是否开通民办和民转公
                    EduFormSpecialQueryVO formSpecialQueryVO = new EduFormSpecialQueryVO();
                    formSpecialQueryVO.setAreaCode(beforeVO.getAreaCode());
                    formSpecialQueryVO.setSmallClassValue(beforeVO.getConfigName());
                    formSpecialQueryVO.setBigClassValue(beforeVO.getConfigTypeName());
                    formSpecialQueryVO.setYear(beforeVO.getYear());
                    EduFormSpecialVO eduFormSpecialVO = eduFormSpecialService.getBySmallValue(formSpecialQueryVO);
                    if(eduFormSpecialVO!=null) {
                        if("港澳台、华侨华人".equalsIgnoreCase(eduFormSpecialVO.getSmallClassValue())){
                            canEnrollFlag=true;
                            preVO.setShowMbFlag(true);
                            preVO.setGatFlag(true);
                        }
                        if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduFormSpecialVO.getMzgFlag())) {
                            preVO.setShowMzgFlag(true);
                        }
                        if (BoolEnum.TRUE.getType().equalsIgnoreCase(eduFormSpecialVO.getMbFlag())) {
                            //民办是否可就读，需要判断是否有户籍
                            //2025年度开放有户籍之外的可以报民办学校
                            //if (preVO.getHouseHoldVO() != null) {
                                preVO.setShowMbFlag(true);
                            //}
                        }
                    }
                }else{
                    if("A".equalsIgnoreCase(beforeVO.getConfigName())
                            ||"B".equalsIgnoreCase(beforeVO.getConfigName())
                            ||"特殊户口".equalsIgnoreCase(beforeVO.getConfigName())){
                        preVO.setShowMbFlag(true);
                        preVO.setShowMzgFlag(true);
                    }
                    if("C".equalsIgnoreCase(beforeVO.getConfigName())){
                        cFlag=true;
                    }
                }
            }
        }
        //处理网签信息
        boolean wqFlag=false;
        if(!CollectionUtils.isEmpty(preVO.getWqList())){
            List<EduNetsignVO> wqList=new ArrayList<>();
            for(EduNetsignVO eduNetsignVO:preVO.getWqList()){
                if(preVO.getAreaCode().equalsIgnoreCase(eduNetsignVO.getAreaCode())&&BoolEnum.TRUE.getType().equalsIgnoreCase(eduNetsignVO.getStatus())){
                    wqList.add(eduNetsignVO);
                    wqFlag=true;
                }
            }
            preVO.setWqList(wqList);

        }
        if(CardTypeEnum.compatriot.getType().equalsIgnoreCase(preVO.getCardType())
                ||CardTypeEnum.passcheck.getType().equalsIgnoreCase(preVO.getCardType())
                ||CardTypeEnum.gapermit.getType().equalsIgnoreCase(preVO.getCardType())
                ||CardTypeEnum.passport.getType().equalsIgnoreCase(preVO.getCardType())
                ||CardTypeEnum.wgridcard.getType().equalsIgnoreCase(preVO.getCardType())){
            //港澳台等同于有户籍
            canEnrollFlag=true;
            preVO.setGatFlag(true);
            preVO.setShowMbFlag(true);
            preVO.setShowMzgFlag(true);
        }
        //处理居住证信息
        boolean fmjzzFlag=false;
        if(!CollectionUtils.isEmpty(preVO.getJzzList())){
            EduOperationCacheQueryVO queryOpVO=new EduOperationCacheQueryVO();
            queryOpVO.setOperating("YW051");
            queryOpVO.setAreaCode(preVO.getAreaCode());
            queryOpVO.setClassify("2");
            EduOperationCacheDetailVO jzzOption=eduSystemConfigIntegration.getEduOperationOne(queryOpVO);
            Integer endTime=0;
            if(jzzOption!=null&&jzzOption.getEndTime()!=null){
                endTime=Integer.parseInt(DateUtil.format(jzzOption.getEndTime(),"YYYYMMDD"));
            }
            List<EduLivePlaceVO> livePlaceList=new ArrayList<>();
            String today = DateUtil.today().replaceAll("-", "");

            for (EduLivePlaceVO eduLivePlaceVO : preVO.getJzzList()) {
                if (StringUtils.isNotBlank(eduLivePlaceVO.getQzdqrq())&&endTime!=0) {
                    if("2".equalsIgnoreCase(eduLivePlaceVO.getZjztdm()) || "3".equalsIgnoreCase(eduLivePlaceVO.getZjztdm()) || "5".equalsIgnoreCase(eduLivePlaceVO.getZjztdm())||"正常".equals(eduLivePlaceVO.getZjzt())) {
                        //到期时间小于截止的，设置为终止
                        Integer qzdqrq = Integer.parseInt(eduLivePlaceVO.getQzdqrq().replaceAll("-", "").replaceAll("/", ""));
                        if (qzdqrq <= endTime) {
                            if (qzdqrq < Integer.parseInt(today)) {
                                eduLivePlaceVO.setZjztdm("5");
                                eduLivePlaceVO.setZjzt("中止");
                            }
                        } else {
                            eduLivePlaceVO.setZjztdm("2");
                            eduLivePlaceVO.setZjzt("正常");
                            if (StringUtils.isNotBlank(eduLivePlaceVO.getQzrq())) {
                                if (Integer.parseInt(eduLivePlaceVO.getQzrq().replaceAll("-", "").replaceAll("/", "")) > endTime&&Integer.parseInt(today)<endTime) {
                                    eduLivePlaceVO.setZjztdm("5");
                                    eduLivePlaceVO.setZjzt("无效");
                                }
                            }

                        }
                    }
                }else{
                    if("正常".equalsIgnoreCase(eduLivePlaceVO.getZjzt())){
                        eduLivePlaceVO.setZjztdm("2");
                    }
                }

                if ("2".equalsIgnoreCase(eduLivePlaceVO.getZjztdm())||"正常".equalsIgnoreCase(eduLivePlaceVO.getZjzt())) {
                    if(StringUtils.isNotBlank(preVO.getFatherIdcard())&&preVO.getFatherIdcard().equalsIgnoreCase(eduLivePlaceVO.getSfzh())){
                        fmjzzFlag=true;
                    }
                    if(StringUtils.isNotBlank(preVO.getMotherIdcard())&&preVO.getMotherIdcard().equalsIgnoreCase(eduLivePlaceVO.getSfzh())){
                        fmjzzFlag=true;
                    }
                    livePlaceList.add(eduLivePlaceVO);
                }
            }
            preVO.setJzzList(livePlaceList);

            if(!CollectionUtils.isEmpty(livePlaceList)){
                if(cFlag){
                    //房产有居住证可以报民转公
                    preVO.setShowMzgFlag(true);
                    //2025年度开放有户籍之外的可以报民办学校
                    preVO.setShowMbFlag(true);
                }
                //2025年度开放只有有孩子居住证就能报名
                canEnrollFlag=true;
                //2024年之前规则
                if(!canEnrollFlag){
                    if(cFlag||wqFlag){
                        canEnrollFlag=true;
                    }else{
                        if (fmjzzFlag||preVO.getHouseholdFmFlag()||preVO.getStudentStatusVO()!=null){
                            canEnrollFlag=true;
                        }
                    }
                }

            }
        }else{
            if(cFlag){
                //房产有居住证可以报民转公
                preVO.setShowMzgFlag(true);
                //2025年度开放有户籍之外的可以报民办学校
                preVO.setShowMbFlag(true);
            }
            if(!canEnrollFlag){
                if(cFlag||wqFlag){
                    canEnrollFlag=true;
                }else{
                    if (fmjzzFlag||preVO.getHouseholdFmFlag()||preVO.getStudentStatusVO()!=null){
                        canEnrollFlag=true;
                    }
                }
            }
        }
        preVO.setFmJzzFlag(fmjzzFlag);
        //2025年度开放父母一方有东阳户籍就能报名
        if (preVO.getHouseholdFmFlag()){
            canEnrollFlag=true;
        }
        //处理房产数据只保留有效数据
        if(!CollectionUtils.isEmpty(preVO.getHouseList())){
            List<EduHouseVO> houseVOList=new ArrayList<>();
            for(EduHouseVO eduHouseVO:preVO.getHouseList()){
                if(BoolEnum.TRUE.getType().equalsIgnoreCase(eduHouseVO.getStatus())&&AuthStatusEnum.YES.getType().equalsIgnoreCase(eduHouseVO.getAuthStatus())){
                    houseVOList.add(eduHouseVO);
                }
            }
            preVO.setHouseList(houseVOList);

        }

        //处理参保数据
        if(!CollectionUtils.isEmpty(preVO.getCbList())){
            List<EduSocialSecurityVO> cbList=new ArrayList<>();
            for(EduSocialSecurityVO eduSocialSecurityVO:preVO.getCbList()){
                if("110".equalsIgnoreCase(eduSocialSecurityVO.getAae140())
                    &&"1".equalsIgnoreCase(eduSocialSecurityVO.getStatus())
                    &&"1".equalsIgnoreCase(eduSocialSecurityVO.getContinuityFlag())){
                    //职工养老
                    cbList.add(eduSocialSecurityVO);
                }
                if("120".equalsIgnoreCase(eduSocialSecurityVO.getAae140())
                        &&"1".equalsIgnoreCase(eduSocialSecurityVO.getStatus())
                        &&"1".equalsIgnoreCase(eduSocialSecurityVO.getContinuityFlag())){
                    //机关养老
                    cbList.add(eduSocialSecurityVO);
                }
            }
            preVO.setCbList(cbList);

        }


        preVO.setZsbEnrollFlag(false);
        if (!canEnrollFlag) {
            if (BoolEnum.TRUE.getType().equalsIgnoreCase(preVO.getPrivateAppointFlag())) {
                EduPrivateAppointStudentVO eduPrivateAppointStudent = preVO.getZsbVO();
                EduStudentEnrollBeforeVO eduStudentEnrollBeforeVO = new EduStudentEnrollBeforeVO();
                eduStudentEnrollBeforeVO.setYear(preVO.getYear());
                eduStudentEnrollBeforeVO.setSchoolId(eduPrivateAppointStudent.getSchoolId());
                EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(eduPrivateAppointStudent.getSchoolId());
                eduStudentEnrollBeforeVO.setSchoolName(eduSchoolVO.getSchoolName());
                eduStudentEnrollBeforeVO.setSchoolCategory(eduSchoolVO.getSchoolCategory());
                eduStudentEnrollBeforeVO.setSchoolNature(eduSchoolVO.getSchoolNature());
                eduStudentEnrollBeforeVO.setConfigTypeName("直升");
                eduStudentEnrollBeforeVO.setStudentEnrollPreId(preVO.getStudentEnrollPreId());
                List<EduStudentEnrollBeforeVO> beforeVOS = new ArrayList<>();
                beforeVOS.add(eduStudentEnrollBeforeVO);
                preVO.setEnrollBeforeList(beforeVOS);
                preVO.setZsbEnrollFlag(true);
            }
        }
        //判断人才
        QueryWrapper<EduTalentPool> talentPoolQueryWrapper = new QueryWrapper<>();
        talentPoolQueryWrapper.lambda().select(EduTalentPool::getTalentId,EduTalentPool::getAreaCode).eq(EduTalentPool::getYear, year);
        if (StringUtils.isNotBlank(preVO.getFatherIdcard())&&StringUtils.isNotBlank(preVO.getMotherIdcard())){
            talentPoolQueryWrapper.lambda().and(wrapper -> wrapper.eq(EduTalentPool::getTalentIdcard, preVO.getFatherIdcard()).or()
                    .eq(EduTalentPool::getTalentIdcard,preVO.getMotherIdcard()));
        }else{
            if (StringUtils.isNotBlank(preVO.getFatherIdcard())){
                talentPoolQueryWrapper.lambda().eq(EduTalentPool::getTalentIdcard, preVO.getFatherIdcard());
            }else if (StringUtils.isNotBlank(preVO.getMotherIdcard())){
                talentPoolQueryWrapper.lambda().eq(EduTalentPool::getTalentIdcard,preVO.getMotherIdcard());
            }
        }
        preVO.setFgFlag(false);
        List<EduTalentPool> eduTalentPoolList = eduTalentPoolService.list(talentPoolQueryWrapper);
        if (!CollectionUtils.isEmpty(eduTalentPoolList)){
            preVO.setFgFlag(true);
            List<String> fgList=new ArrayList<>();
            for (EduTalentPool talentPool:eduTalentPoolList){
                if (StringUtils.isBlank(talentPool.getAreaCode())){
                    fgList=new ArrayList<>();
                    break;
                }else{
                    if (!fgList.contains(talentPool.getAreaCode())){
                        fgList.add(talentPool.getAreaCode());
                    }
                }
            }
            preVO.setFgAreaCodeList(fgList);
        }

        if(canEnrollFlag){
            preVO.setCanEnroll(BoolEnum.TRUE.getType());
            //2025年度开放有户籍之外的可以报民办学校
            preVO.setShowMbFlag(true);
        }
        //处理报名数据
        preVO.setCanEnrollFlag(canEnrollFlag);
        return preVO;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0059", title = "家长端查询可报名的人员信息批量", funcType = FuncTypeEnum.query)
    public List<EduStudentEnrollPreVO> getBeforeBatch(BmQueryVO vo) {
        List<BmStudentVO> bmStudentVOList = getPreListByToken(vo);
        List<EduStudentEnrollPreVO> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(bmStudentVOList)) {
            return list;
        }
        for (BmStudentVO bmStudentVO : bmStudentVOList) {
            EduStudentEnrollPreKeyVO keyVO = new EduStudentEnrollPreKeyVO();
            keyVO.setStudentEnrollPreId(bmStudentVO.getStudentEnrollPreId());
            keyVO.setAccessToken(vo.getAccessToken());
            EduStudentEnrollPreVO preVO = getBeforeByPreId(keyVO);
            list.add(preVO);

        }
        return list;
    }

    /** 保存前统一校验*/
    @Override
    @OpApi(funcCode = "eduStudentEnroll0003", title = "学生正式报名管理保存前校验", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void checkSave(SaveStudentEnrollVO vo) {


    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0004", title = "学生正式报名管理线下录入报名", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduStudentEnroll0004",
            operationName = "学生正式报名管理线下录入报名",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public SaveStudentEnrollVO add(SaveStudentEnrollVO vo) {
        vo.setLrFlag(true);
        return saveEnroll(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0019", title = "app端家长报名保存", funcType = FuncTypeEnum.insert)
    @SaveOplog(
            operationType = "eduStudentEnroll0019",
            operationName = "app端家长报名保存",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public SaveStudentEnrollVO saveEnrollApp(SaveStudentEnrollVO vo) {
        vo.setLrFlag(false);
        return saveEnroll(vo);
    }
    //动态调用报名个性化方法
    private SaveStudentEnrollVO saveEnroll(SaveStudentEnrollVO vo){
        EduSchoolVO schoolVO=eduSchoolService.getDetail(vo.getSchoolId());
        if(schoolVO==null){
            throw new AppException("报名的学校不存在");
        }
        EduSystemConfigFuncQueryVO queryVO=new EduSystemConfigFuncQueryVO();
        queryVO.setAccessToken(vo.getAccessToken());
        queryVO.setAreaCode(schoolVO.getAreaCode());
        queryVO.setEduConfigKey("saveEnroll");
        String funcCode=eduSystemConfigIntegration.getFuncCode(queryVO);
        ApiModel apiModel=apiContainer.get(funcCode);
        if(apiModel!=null){
            try {
                Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
                if (null != bean) {
                    apiModel.getMethod().invoke(bean, vo);
                    eduEnrollClearCacheHelper.clearCacheMyEnroll(vo.getIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnroll(vo.getFatherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnroll(vo.getMotherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(vo.getIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(vo.getFatherIdcard());
                    eduEnrollClearCacheHelper.clearCacheMyEnrollPre(vo.getMotherIdcard());
                    eduEnrollClearCacheHelper.clearCachePreBefore(vo.getStudentEnrollPreId());
                }else {
                    throw new AppException(schoolVO.getAreaCode()+"未找到处理报名保存的个性化方法");
                }
            }catch (AppException e ){
                throw e;
            }catch (InvocationTargetException e ){
                try{
                    AppException exception= (AppException) e.getTargetException();
                    throw new AppException(exception.getMsg(),e.getTargetException());
                }catch (Exception ex){
                    throw new AppException(e.getCause().getMessage(),e.getTargetException());
                }

            }catch (Exception e ){
                throw new AppException( e.getMessage());
            }
        }else {
            throw new AppException(schoolVO.getAreaCode()+"未找到处理报名保存的个性化方法");
        }
        return vo;
    }
    @Override
    @OpApi(funcCode = "eduStudentEnroll0005", title = "学生正式报名管理修改", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0005",
            operationName = "学生正式报名管理修改",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public EduStudentEnrollVO edit(EduStudentEnrollVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getAuthStatus())) {
            throw new AppException("审核状态不能为空");
        }
        //判断数据是否已经迁移
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(), STUDENT_ENROLL_TABLE);
        if (!queryHistoryFlag) {
            EduStudentEnroll old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
            if (old == null) {
                throw new AppException("报名数据不存在，可能已被退回");
            }
        } else {
            throw new AppException("历史数据无法修改");
        }
        EduStudentEnroll studentEnroll = Convert.convert(EduStudentEnroll.class, vo);
        //处理传值为false或true时报长度错误
        if (StringUtils.isNotBlank(studentEnroll.getQyFlag())&& studentEnroll.getQyFlag().equalsIgnoreCase("true")) {
            studentEnroll.setQyFlag(BoolEnum.TRUE.getType());
        } else {
            studentEnroll.setQyFlag(BoolEnum.FALSE.getType());
        }
        if (AuthStatusEnum.NODO.getType().equals(studentEnroll.getAuthStatus())) {
            //待审核
            studentEnroll.setAdmitFlag(null);
            studentEnroll.setAdmitTime(null);
            studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());

        }
        if (AuthStatusEnum.NO.getType().equals(studentEnroll.getAuthStatus())) {
            //审核不通过
            studentEnroll.setAdmitFlag(BoolEnum.FALSE.getType());
            studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
            if (studentEnroll.getAdmitTime() == null) {
                studentEnroll.setAdmitTime(new Date());
            }
            studentEnroll.setAdmitUserId(SessionUtil.getUserId());
        }
        if (AuthStatusEnum.YES.getType().equals(studentEnroll.getAuthStatus())) {
            if (StringUtils.isBlank(studentEnroll.getAdmitFlag()) || "2".equals(studentEnroll.getAdmitFlag())) {
                studentEnroll.setAdmitFlag(null);
                studentEnroll.setAdmitTime(null);
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dlq.getType());
            } else if (BoolEnum.TRUE.getType().equals(studentEnroll.getAdmitFlag())) {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.lq.getType());
                if (studentEnroll.getAdmitTime() == null) {
                    studentEnroll.setAdmitTime(new Date());
                }
            } else {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
                if (studentEnroll.getAdmitTime() == null) {
                    studentEnroll.setAdmitTime(new Date());
                }
            }
        }
        eduStudentEnrollService.updateById(studentEnroll);
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getMotherIdcard());
        return vo;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0006", title = "学生正式报名管理根据主键删除", funcType = FuncTypeEnum.delete)
    @SaveOplog(
            operationType = "eduStudentEnroll0006",
            operationName = "学生正式报名管理删除",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void del(EduStudentEnrollKeyVO vo) {
        if (ObjectUtils.isEmpty(vo.getStudentEnrollId())) {
            throw new AppException("传入需要删除的数据主键不能为空!");
        }
        EduStudentEnroll entity = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (ObjectUtils.isEmpty(entity)) {
            throw new AppException("未找到需要删除的信息!");
        }
        eduStudentEnrollService.removeById(vo.getStudentEnrollId());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(entity.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(entity.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(entity.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(entity.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(entity.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(entity.getMotherIdcard());
        QueryWrapper<EduStudentEnrollPre> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduStudentEnrollPre::getStudentEnrollPreId)
                .eq(EduStudentEnrollPre::getIdcard,entity.getIdcard())
                .eq(EduStudentEnrollPre::getYear,entity.getYear());
        EduStudentEnrollPre pre=eduStudentEnrollPreService.getOne(queryWrapper,false);
        if(pre!=null){
            eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
        }

    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0007", title = "app端判断登录账号是否学生", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public Boolean UserIsStudent(BaseVO vo) {
        String idcard= SessionUtil.getSessionInfo().getIdcard();
        EduOperationCacheDetailVO eduOperationCacheDetailVO=operationCacheIntegration.getPeriodYear();
        Integer year=eduOperationCacheDetailVO.getYear();
        QueryWrapper<EduStudentEnrollPre> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduStudentEnrollPre::getIdcard,idcard)
        .eq(EduStudentEnrollPre::getYear,year);
        return eduStudentEnrollPreService.count(queryWrapper)>0;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0049", title = "app端判断是否可以摇号绑定", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public List<BindEnrollVO> checkBind(BindEnrollQueryVO vo) {
        if(StringUtils.isBlank(vo.getSchoolId())){
            throw new AppException("报名学校id不能为空");
        }
        if(StringUtils.isBlank(vo.getStudentEnrollPreId())){
            throw new AppException("当前报名人员id不能为空");
        }
        EduStudentEnrollPreKeyVO keyVO=Convert.convert(EduStudentEnrollPreKeyVO.class,vo);
        EduStudentEnrollPreVO preVO=eduStudentEnrollBeforeIntegration.getPreDetail(keyVO);
        String idcard=SessionUtil.getSessionInfo().getIdcard();
        Integer year =eduHelper.thisYear();
        QueryWrapper<EduStudentEnroll> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduStudentEnroll::getIdcard,EduStudentEnroll::getFullName,EduStudentEnroll::getBindFlag,EduStudentEnroll::getConfigTypeName,EduStudentEnroll::getConfigName)
                .eq(EduStudentEnroll::getSchoolId,vo.getSchoolId())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getBirthYmd,preVO.getBirthYmd())
                .eq(EduStudentEnroll::getFatherIdcard,idcard)
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.dsh.getType());
        List<EduStudentEnroll> faList=eduStudentEnrollService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(faList)){
            return Convert.toList(BindEnrollVO.class,faList);
        }
        QueryWrapper<EduStudentEnroll> moQuery=new QueryWrapper<>();
        moQuery.lambda().select(EduStudentEnroll::getIdcard, EduStudentEnroll::getFullName, EduStudentEnroll::getBindFlag, EduStudentEnroll::getConfigTypeName, EduStudentEnroll::getConfigName).eq(EduStudentEnroll::getSchoolId, vo.getSchoolId())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getMotherIdcard,idcard)
                .eq(EduStudentEnroll::getBirthYmd,preVO.getBirthYmd())
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.dsh.getType());
        List<EduStudentEnroll> moList=eduStudentEnrollService.list(moQuery);
        if(!CollectionUtils.isEmpty(moList)){
            return Convert.toList(BindEnrollVO.class,moList);
        }
        return new ArrayList<>();
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0008", title = "app端我的报名查询", funcType = FuncTypeEnum.query,checkPrivilege = BoolEnum.FALSE)
    public List<MyYearEnrollVO> getMyEnrollInfo(MyEnrollQueryVO vo) {

        //是否允许查看我的报名
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("queryEnrollFlag");
        String queryEnrollFlag = commonIntegration.getValueByKey(commonVO);
        if("0".equals(queryEnrollFlag)){
            return new ArrayList<>();
        }


        if(vo.getHiddenFlag()==null){
            vo.setHiddenFlag(true);
        }
        String idcard = SessionUtil.getSessionInfo().getIdcard();
        List<StudentFormVO> myEnrollInfo = eduStudentEnrollKindergartenService.getMyNurseryInfo(idcard);
        if(CollectionUtils.isEmpty(myEnrollInfo)){
            return new ArrayList<>();
        }
        dictHelper.valueToName(myEnrollInfo, Arrays.asList(EduStudentEnrollDictEnum.values()));
        //调用个性化处理
        Map<String, List<StudentFormVO>> areaCodeGroupBy = myEnrollInfo.stream().collect(Collectors.groupingBy(StudentFormVO::getAreaCode));
        for(String areaCode:areaCodeGroupBy.keySet()){
            EduSystemConfigFuncQueryVO queryVO=new EduSystemConfigFuncQueryVO();
            queryVO.setAccessToken(vo.getAccessToken());
            queryVO.setAreaCode(areaCode);
            queryVO.setEduConfigKey("getMyEnrollInfo");
            String funcCode=eduSystemConfigIntegration.getFuncCode(queryVO);
            ApiModel apiModel=apiContainer.get(funcCode);
            if(apiModel!=null){
                try {
                    Object bean = ApplicationContextHelper.getBean(apiModel.getBeanName());
                    if (null != bean) {
                         apiModel.getMethod().invoke(bean, areaCodeGroupBy.get(areaCode));
                    }else {
                        throw new AppException(areaCode+"未找到处理我的报名的个性化方法");
                    }
                }catch (AppException e ){
                    throw e;
                }catch (InvocationTargetException e ){
                    try{
                        AppException exception= (AppException) e.getTargetException();
                        throw new AppException(exception.getMsg(),e.getTargetException());
                    }catch (Exception ex){
                        throw new AppException(e.getCause().getMessage(),e.getTargetException());
                    }

                }catch (Exception e ){
                    throw new AppException( e.getMessage(),e);
                }
            }else {
                throw new AppException(areaCode+"未找到处理我的报名的个性化方法");
            }
        }
        Integer year = eduHelper.thisYear();
        Map<Integer, List<StudentFormVO>> yearGroupBy = myEnrollInfo.stream().collect(Collectors.groupingBy(StudentFormVO::getYear));
        List<MyYearEnrollVO> mapList=new ArrayList<>();
        for(Integer key:yearGroupBy.keySet()){
            MyYearEnrollVO myYearEnrollVO=new MyYearEnrollVO();
            myYearEnrollVO.setYear(key);
            List<StudentFormVO> xsList=yearGroupBy.get(key);
            List<MyEnrollVO> myEnrollVOList=new ArrayList<>();
            if(!CollectionUtils.isEmpty(xsList)){
                Map<String, List<StudentFormVO>> xsGroupBy = xsList.stream().collect(Collectors.groupingBy(StudentFormVO::getChildIdcard));
                for(String xs:xsGroupBy.keySet()){
                    List<StudentFormVO> bmList=xsGroupBy.get(xs);
                    if(!CollectionUtils.isEmpty(bmList)){
                        MyEnrollVO myEnrollVO=Convert.convert(MyEnrollVO.class,bmList.get(0));
                        if(vo.getHiddenFlag()){
                            myEnrollVO.setChildIdcard(DesensitizeUtil.getIdcard(myEnrollVO.getChildIdcard()));
                            myEnrollVO.setChildFullName(DesensitizeUtil.getFullName(myEnrollVO.getChildFullName()));
                        }
                        for (StudentFormVO formVO : bmList) {
                            formVO.setEnrollNum(1);
                            if(BoolEnum.TRUE.getType().equalsIgnoreCase(formVO.getBbFlag())){
                                formVO.setEnrollNum(2);
                            }
                            if(BoolEnum.TRUE.getType().equalsIgnoreCase(formVO.getSpareRegisterFlag())){
                                formVO.setEnrollNum(3);
                            }
                            if (year - formVO.getYear() == 0 && SchoolNatureEnum.gb.getType().equalsIgnoreCase(formVO.getSchoolNature())
                                    && EnrollStatusFormalEnum.ywblq.getType().equalsIgnoreCase(formVO.getEnrollStatus())
                                    && AuthStatusEnum.YES.getType().equalsIgnoreCase(formVO.getAuthStatus())) {
                                //查询调剂时间
                                EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
                                queryVO.setOperating("YW059");
                                queryVO.setAreaCode(formVO.getAreaCode());
                                queryVO.setYear(year);
                                queryVO.setClassify("2");
                                EduOperationCacheDetailVO bmOption = eduSystemConfigIntegration.getEduOperationOne(queryVO);
                                boolean tjTimeFlag = false;
                                if (bmOption == null) {
                                    tjTimeFlag = false;
                                } else {
                                    if (bmOption.isFlag()) {
                                        tjTimeFlag = true;
                                    }else{
                                        if ("2".equalsIgnoreCase(bmOption.getType())){
                                            tjTimeFlag = true;
                                        }
                                    }
                                }
                                if (tjTimeFlag) {
                                    //业务不予录取，查询是否可调剂
                                    QueryWrapper<EduSchoolTj> queryWrapper = new QueryWrapper<>();
                                    queryWrapper.lambda().eq(EduSchoolTj::getFromSchoolId, formVO.getSchoolId())
                                            .eq(EduSchoolTj::getFromConfigName, formVO.getConfigName())
                                            .eq(EduSchoolTj::getFlag, BoolEnum.TRUE.getType())
                                            .eq(EduSchoolTj::getYear, formVO.getYear());
                                    formVO.setTjStatus("1");//默认设置不能调剂
                                    if (eduSchoolTjService.count(queryWrapper) > 0) {
                                        formVO.setTjStatus("2");//待申请
                                        //判断是否调剂申请
                                        QueryWrapper<EduStudentTj> tjQueryWrapper = new QueryWrapper<>();
                                        tjQueryWrapper.lambda().eq(EduStudentTj::getStudentEnrollId, formVO.getStudentEnrollId())
                                                .orderByAsc(EduStudentTj::getTjType, EduStudentTj::getAspirationType);
                                        List<EduStudentTj> eduStudentTjList = eduStudentTjService.list(tjQueryWrapper);
                                        if (!CollectionUtils.isEmpty(eduStudentTjList)) {
                                            formVO.setTjList(Convert.toList(EduStudentTjVO.class, eduStudentTjList));
                                            for (EduStudentTj tj : eduStudentTjList) {
                                                if (BoolEnum.TRUE.getType().equalsIgnoreCase(tj.getCurrentFlag())) {
                                                    if (AuthStatusEnum.NODO.getType().equalsIgnoreCase(tj.getAuthStatus())) {
                                                        formVO.setTjStatus("3");//已申请
                                                    }
                                                    if (AuthStatusEnum.YES.getType().equalsIgnoreCase(tj.getAuthStatus())) {
                                                        formVO.setTjStatus("4");//调剂完成
                                                    }
                                                    break;
                                                }

                                            }
                                        }
                                    }
                                } else {
                                    formVO.setTjStatus("1");
                                }
                            } else {
                                formVO.setTjStatus("1");
                            }
                            if (StringUtils.isBlank(formVO.getConfigName())) {
                                formVO.setConfigName(formVO.getConfigTypeName());
                            }
                            if (StringUtils.isBlank(formVO.getConfigNameAlias())) {
                                formVO.setConfigNameAlias(formVO.getConfigName());
                            }

                        }
                        myEnrollVO.setEnrollList(bmList);
                        myEnrollVOList.add(myEnrollVO);
                    }
                }
            }
            if(!CollectionUtils.isEmpty(myEnrollVOList)){
                myYearEnrollVO.setEnrollList(myEnrollVOList);
                mapList.add(myYearEnrollVO);
            }
            //降序
            mapList.sort(Comparator.comparing(MyYearEnrollVO::getYear).reversed());
        }
        return mapList;
    }
    @Override
    @OpApi(funcCode = "eduStudentEnroll0009", title = "查询校验报名情况", funcType = FuncTypeEnum.query)
    public Boolean checkEnroll(YjbmQueryVO vo) {
        EduStudentEnrollPre eduStudentEnrollPre= getPre(vo.getStudentEnrollPreId(),vo.getIdcard());
        if(eduStudentEnrollPre==null){
            throw new AppException("未找到新生登记信息");
        }
        return this.checkEnroll(eduStudentEnrollPre);
    }

    @Override
    public Boolean checkEnroll(EduStudentEnrollPre eduStudentEnrollPre) {
        return checkEnroll(eduStudentEnrollPre.getIdcard(),eduStudentEnrollPre.getYear());

    }

    @Override
    public Boolean checkEnroll(String idcard, Integer year) {
        if(year==null){
            EduOperationCacheDetailVO eduOperationCacheDetailVO=operationCacheIntegration.getPeriodYear();
            year=eduOperationCacheDetailVO.getYear();
        }
        List<String> enrollStatusList=new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper =new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnroll::getIdcard).eq(EduStudentEnroll::getIdcard,idcard)
                .eq(EduStudentEnroll::getYear,year)
                .in(EduStudentEnroll::getEnrollStatus,enrollStatusList);
        if(eduStudentEnrollService.count(enrollQueryWrapper)<=0){
            return false;
        }
        return true;
    }

    @Override
    public Boolean hasEnroll(String idcard, Integer year) {
        if(year==null){
            EduOperationCacheDetailVO eduOperationCacheDetailVO=operationCacheIntegration.getPeriodYear();
            year=eduOperationCacheDetailVO.getYear();
        }

        QueryWrapper<EduStudentEnroll> enrollQueryWrapper =new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnroll::getIdcard).eq(EduStudentEnroll::getIdcard,idcard)
                .eq(EduStudentEnroll::getYear,year);
        if(eduStudentEnrollService.count(enrollQueryWrapper)<=0){
            return false;
        }
        return true;
    }

    @Override
    public EduStudentEnrollPre getPre(String studentEnrollPreId,String idcard){

        if(StringUtils.isNotBlank(studentEnrollPreId)){
            EduStudentEnrollPre eduStudentEnrollPre =
                    eduStudentEnrollPreService.getById(studentEnrollPreId);
            if (eduStudentEnrollPre == null) {
                throw new AppException("未找到预采集数据");
            }
            if (!AuthStatusEnum.YES.getType().equals(eduStudentEnrollPre.getAuthStatus())) {
                throw new AppException("该预采集未审核或者审核不通过");
            }
            return eduStudentEnrollPre;
        }
        if(StringUtils.isNotBlank(idcard)){
            Integer year=eduHelper.thisYear();
            QueryWrapper<EduStudentEnrollPre> queryWrapper=new QueryWrapper<>();
            queryWrapper.lambda().eq(EduStudentEnrollPre::getIdcard,idcard)
                    .eq(EduStudentEnrollPre::getYear,year)
                    .eq(EduStudentEnrollPre::getAuthStatus,AuthStatusEnum.YES.getType());
            List<EduStudentEnrollPre> list=eduStudentEnrollPreService.list(queryWrapper);
            if (CollectionUtils.isEmpty(list)){
                throw new AppException("未找到有效的学生数据，请先办理准新生登记");
            }else{
                if(list.size()>1){
                    throw new AppException("存在多条数据，请联系学校或者技术人员");
                }
                return list.get(0);
            }
        }else{
            throw new AppException("学生身份证或者预采集信息不能为空");
        }

    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0010", title = "校验是否可以摇号导出", funcType = FuncTypeEnum.query)
    @NoSignCrypto
    public void checkYhExp(EduStudentEnrollQueryVO vo) {
        String schoolId=vo.getSchoolId();
        if(StringUtils.isBlank(schoolId)){
            schoolId=SessionUtil.getSessionInfo().getOrgId();
        }
        if(StringUtils.isBlank(vo.getConfigTypeName())){
            throw new AppException("请先选择报名类型");
        }
        int year = eduHelper.thisYear();

        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        //判断是否有未审核数据
        QueryWrapper<EduStudentEnroll> wshQuery=new QueryWrapper<>();
        wshQuery.lambda().eq(EduStudentEnroll::getSchoolId,schoolId)
                .eq(EduStudentEnroll::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.dsh.getType())
                .eq(StringUtils.isNotBlank(vo.getAspirationType()),EduStudentEnroll::getAspirationType,vo.getAspirationType());
        long wshCount=eduStudentEnrollService.count(wshQuery);
        if(wshCount>0){
            throw new AppException("存在未审核数据，请先审核后导出");
        }
        //判断是否存在摇号排序号，存在的情况下不允许导出
        QueryWrapper<EduStudentEnroll> pxhQuery=new QueryWrapper<>();
        pxhQuery.lambda().eq(EduStudentEnroll::getSchoolId,schoolId)
                .eq(EduStudentEnroll::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType())
                .isNotNull(EduStudentEnroll::getSerialNum)
                .eq(StringUtils.isNotBlank(vo.getAspirationType()),EduStudentEnroll::getAspirationType,vo.getAspirationType());
        long pxhCount=eduStudentEnrollService.count(pxhQuery);
        if(pxhCount>0){
            throw new AppException("已存在摇号排序号，不能导出");
        }
        //判断审核通过是否大于计划数

        //待录取人数
        QueryWrapper<EduStudentEnroll> dlqQuery=new QueryWrapper<>();
        dlqQuery.lambda().eq(EduStudentEnroll::getSchoolId,schoolId)
                .eq(EduStudentEnroll::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType())
                .eq(StringUtils.isNotBlank(vo.getAspirationType()),EduStudentEnroll::getAspirationType,vo.getAspirationType());
        long dlyCount=eduStudentEnrollService.count(dlqQuery);
        if(dlyCount==0){
            throw new AppException("没有待录取数据，不能导出");
        }
        QueryWrapper<EduSchoolConfig> configQueryWrapper=new QueryWrapper<>();
        configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment, EduSchoolConfig::getSerialNumEnd)
                .eq(EduSchoolConfig::getSchoolId,schoolId)
                .eq(EduSchoolConfig::getAreaCode,vo.getAreaCode())
                .eq(EduSchoolConfig::getYear,year)
                .eq(EduSchoolConfig::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getStatus,BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getConfigTypeName,vo.getConfigTypeName());
        QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper=new QueryWrapper<>();
        brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,year)
                .eq(EduEnrollmenBrochure::getSchoolId,schoolId);
        EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(brochureQueryWrapper,false);
        if(eduEnrollmenBrochure==null){
            throw new AppException("未找到招生方案信息");
        }
        EduSchool eduSchool=eduSchoolService.getById(schoolId);
        if("1".equals(eduSchool.getSchoolNature())){
            //民办
            if("1".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("第一志愿招生已停止，不能导出");
                }
            }else if("2".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
                    throw new AppException("第二志愿招生已停止，不能导出");
                }
            }else if("3".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
                    throw new AppException("第三志愿招生已停止，不能导出");
                }
            }else if("4".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())){
                    throw new AppException("第四志愿招生已停止，不能导出");
                }
            }else{
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("招生已停止，不能导出");
                }
            }
        }else{
            if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                throw new AppException("招生已停止，不能导出");
            }
        }


        EduSchoolConfig eduSchoolConfig=eduSchoolConfigService.getOne(configQueryWrapper,false);
        if(eduSchoolConfig==null){
            throw new AppException("未配置招生计划");
        }
        //计划人数
        Integer enrolment=0;
        if(eduSchoolConfig!=null){
            enrolment=eduSchoolConfig.getEnrolment()==null?0:eduSchoolConfig.getEnrolment();
        }
        //已录取人数
        QueryWrapper<EduStudentEnroll> ylqQuery=new QueryWrapper<>();
        ylqQuery.lambda().eq(EduStudentEnroll::getSchoolId,schoolId)
                .eq(EduStudentEnroll::getAreaCode,vo.getAreaCode())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.lq.getType());
        long ylqCount=eduStudentEnrollService.count(ylqQuery);

        if(ylqCount+dlyCount<=enrolment){
            throw new AppException("录取人数小于计划数，无需摇号");
        }
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0011", title = "义务教育民转公报名摇号信息导出", funcType = FuncTypeEnum.other)
    public void exportYwMzgApplyInfo(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        vo.setOpType("2");
        this.exportYwApplyInfo(vo,response);
    }



    @Override
    @OpApi(funcCode = "eduStudentEnroll0012", title = "义务教育民转公摇号信息导入", funcType = FuncTypeEnum.other)
    public YwMbApplyFileVO inputYwMzgApplyInfo(YwMbApplyFileVO vo, MultipartFile file) {
       return this.inputYwMbApplyInfo(vo,file);
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0013", title = "获取义务教育报名单个明细", funcType = FuncTypeEnum.query)
    public EduStudentEnrollVO getYwApplyDetail(EduStudentEnrollKeyVO vo) {

        return this.getYwApplyById(vo);
    }

    @Override
    public EduStudentEnrollVO getYwApplyById(EduStudentEnrollKeyVO vo) {
        String studentEnrollId = vo.getStudentEnrollId();
        Assert.hasText(studentEnrollId, "义务教育学生报名id不能为空");
        EduStudentEnrollQueryVO queryVO = new EduStudentEnrollQueryVO();
        queryVO.setStudentEnrollId(studentEnrollId);
        if(vo.getYear()==null){
            vo.setYear(eduHelper.thisYear());
        }
        List<EduStudentEnrollVO> list = new ArrayList<>();
        //判断是否迁移
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),STUDENT_ENROLL_TABLE);
        if (!queryHistoryFlag) {
            list = eduStudentEnrollService.getYwApplyList(queryVO);
            if (CollectionUtils.isEmpty(list)) {
                throw new AppException("未找到报名信息，请刷新页面后重新再试");
            }
        } else {
            list = eduhStudentEnrollService.getYwApplyListYq(queryVO);
            if (CollectionUtils.isEmpty(list)) {
                throw new AppException("未找到报名信息，请刷新页面后重新再试");
            }
            //解密
            for (EduStudentEnrollVO studentEnroll : list) {
                if ("1".equals(studentEnroll.getEncryptFlag())){
                    eduStudentEnrollService.decrypt(studentEnroll);
                }
            }
        }
        EduStudentEnrollVO studentEnrollVO = Convert.convert(EduStudentEnrollVO.class, list.get(0));
        QueryWrapper<EduStudentEnrollVerification> queryVWrapper=new QueryWrapper<>();
        queryVWrapper.lambda().eq(EduStudentEnrollVerification::getStudentEnrollId,studentEnrollVO.getStudentEnrollId());
        List<EduStudentEnrollVerification> verificationList=eduStudentEnrollVerificationService.list(queryVWrapper);
        if (!CollectionUtils.isEmpty(list)){
            studentEnrollVO.setVerificationVOList(Convert.toList(EduStudentEnrollVerificationVO.class,verificationList));
        }else{
            studentEnrollVO.setVerificationVOList(new ArrayList<>());
        }
        /*
        * source:6 学校录入报名数据
        * */
        if(StringUtils.isNotEmpty(studentEnrollVO.getSource())){
            if("6".equals(studentEnrollVO.getSource())){
                studentEnrollVO.setFileInfo(studentEnrollVO.getParam20());
            }
        }

        String formId = studentEnrollVO.getFormId();
        if ("0".equals(studentEnrollVO.getSchoolNature())
                &&!BoolEnum.TRUE.getType().equals(studentEnrollVO.getSpecialFlag())
                &&!BoolEnum.TRUE.getType().equals(studentEnrollVO.getSpareRegisterFlag())
                &&!"直升".equals(studentEnrollVO.getConfigName())
                && ObjectUtils.isEmpty(formId)) {
            throw new AppException("数据异常：报名表单id为空，请联系系统管理员");
        }
        EduStudentEnroll gbEnroll = null;
        if (StringUtils.isNotBlank(studentEnrollVO.getParentId())) {
            QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduStudentEnroll::getStudentEnrollId, studentEnrollVO.getParentId())
                    .eq(EduStudentEnroll::getSchoolNature,"0");
            List<EduStudentEnroll> eduStudentEnrollList = eduStudentEnrollService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(eduStudentEnrollList)) {
                gbEnroll = eduStudentEnrollList.get(0);
                String cqSchool = "all";
                if (StringUtils.isNotBlank(cqSchool)) {
                    boolean setFlag = false;
                    if (!"all".equals(cqSchool)) {
                        List<String> schoolIdList = Arrays.stream(cqSchool.split(",")).map(s -> s).collect(Collectors.toList());
                        if (schoolIdList.contains(gbEnroll.getSchoolId())) {
                            setFlag = true;
                        }
                    } else {
                        setFlag = true;
                    }

                    if (setFlag) {
                        studentEnrollVO.setGbConfigName(gbEnroll.getConfigName());
                        EduSchoolVO eduSchool = eduSchoolService.getDetail(gbEnroll.getSchoolId());
                        if (eduSchool != null) {
                            studentEnrollVO.setGbSchoolName(eduSchool.getSchoolName());
                        }

                    }
                }
            }

        } else {
            if("0".equals(studentEnrollVO.getSchoolNature())){
                gbEnroll = Convert.convert(EduStudentEnroll.class, studentEnrollVO);
            }
        }

        int year = studentEnrollVO.getYear();
        List<EduFormEnrollParams> configList = null;
        if(gbEnroll!=null){
            if (BoolEnum.TRUE.getType().equals(gbEnroll.getSpecialFlag())) {
                //特殊通道
                QueryWrapper<EduFormSpecialParams> configQueryWrapper = new QueryWrapper<>();
                configQueryWrapper.lambda().eq(EduFormSpecialParams::getFormSpecialId, formId);
                List<EduFormSpecialParams> formSpecialList = eduFormSpecialParamsService.list(configQueryWrapper);
                if (!CollectionUtils.isEmpty(formSpecialList)) {
                    configList = Convert.toList(EduFormEnrollParams.class, formSpecialList);
                }
            } else {
                QueryWrapper<EduFormEnrollParams> configQueryWrapper = new QueryWrapper<>();
                configQueryWrapper.lambda().eq(EduFormEnrollParams::getFormId, formId);
                configList = eduFormEnrollParamsService.list(configQueryWrapper);
            }
        }

        studentEnrollVO.setXjFlag(false);
        studentEnrollVO.setSbFlag(false);
        studentEnrollVO.setHjFlag(false);
        studentEnrollVO.setFcFlag(false);
        studentEnrollVO.setQyFlag(false);
        studentEnrollVO.setJzzFlag(false);
        studentEnrollVO.setWqFlag(false);
        studentEnrollVO.setHjDsjFlag(false);
        studentEnrollVO.setFcDsjFlag(false);
        List<EduFormEnrollParamsVO> formConfigVOList = new ArrayList<>();
        List<String> idcardList = new ArrayList<>();
        if (gbEnroll!=null&&"0".equals(gbEnroll.getSchoolNature())) {
            idcardList.add(gbEnroll.getIdcard());
            if (StringUtils.isNotBlank(gbEnroll.getFatherIdcard())) {
                idcardList.add(gbEnroll.getFatherIdcard());
            }
            if (StringUtils.isNotBlank(gbEnroll.getMotherIdcard())) {
                idcardList.add(gbEnroll.getMotherIdcard());
            }
            //公办学校处理
            if ("A".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setHjFlag(true);
                studentEnrollVO.setFcFlag(true);
            }
            if ("B".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setHjFlag(true);
            }
            if ("C".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setFcFlag(true);
            }
            if ("特殊户口".equals(gbEnroll.getConfigName())) {
                studentEnrollVO.setHjFlag(true);
            }
            if ("E".equals(gbEnroll.getConfigName()) && BoolEnum.TRUE.getType().equalsIgnoreCase(gbEnroll.getAppointFlag())) {
                studentEnrollVO.setXjFlag(true);
            }

            if (!CollectionUtils.isEmpty(configList)) {
                configList.forEach(item -> {
                    if (StringUtils.equals(item.getPropertyType(), "4")) {
                        studentEnrollVO.setXjFlag(true);
                    } else if (StringUtils.equals(item.getPropertyType(), "5")) {
                        studentEnrollVO.setHjFlag(true);
                    } else if (StringUtils.equals(item.getPropertyType(), "6")) {
                        studentEnrollVO.setFcFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "7")) {
                        studentEnrollVO.setWqFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "8")) {

                        studentEnrollVO.setSbFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "9")) {

                        studentEnrollVO.setQyFlag(true);

                    } else if (StringUtils.equals(item.getPropertyType(), "10")) {

                        studentEnrollVO.setJzzFlag(true);

                    } else {
                        formConfigVOList.add(Convert.convert(EduFormEnrollParamsVO.class, item));
                    }
                });

            }

            if(studentEnrollVO.getWqFlag()){
                //网签
                if (StringUtils.isNotBlank(gbEnroll.getNetsignId())) {
                    QueryWrapper<EduNetsign> netsignQueryWrapper = new QueryWrapper<>();
                    netsignQueryWrapper.lambda().eq(EduNetsign::getYear, year)
                            .eq(EduNetsign::getNetsignId, gbEnroll.getNetsignId())
                            .orderByAsc(EduNetsign::getBasj);
                    List<EduNetsign> netsignList = eduNetsignService.list(netsignQueryWrapper);
                    if (!CollectionUtils.isEmpty(netsignList)) {
                        List<EduNetsignVO> netsignVOList = Convert.toList(EduNetsignVO.class, netsignList);
                        for (EduNetsignVO eduNetsignVO : netsignVOList) {
                            if (StringUtils.isNotBlank(eduNetsignVO.getSchoolId())) {
                                EduSchoolVO eduSchool = eduSchoolService.getDetail(eduNetsignVO.getSchoolId());
                                if (eduSchool != null) {
                                    eduNetsignVO.setSchoolName(eduSchool.getSchoolName());
                                }
                            }
                        }
                        studentEnrollVO.setWqList(netsignVOList);
                    }
                }
            }
            if(studentEnrollVO.getSbFlag()){
                //社保
                if (StringUtils.isNotBlank(gbEnroll.getSocialSecurityId())) {
                    QueryWrapper<EduSocialSecurity> securityQueryWrapper = new QueryWrapper<>();
                    securityQueryWrapper.lambda().eq(EduSocialSecurity::getYear, year)
                            .eq(EduSocialSecurity::getAab301, gbEnroll.getAreaCode())
                            .in(EduSocialSecurity::getAac147, idcardList)
                            .eq(EduSocialSecurity::getAac031, "1")
                            .eq(EduSocialSecurity::getAac008, "1")
                            .orderByAsc(EduSocialSecurity::getAac147).orderByAsc(EduSocialSecurity::getAae140).orderByAsc(EduSocialSecurity::getAae030);
                    List<EduSocialSecurity> socialSecurityList = eduSocialSecurityService.list(securityQueryWrapper);
                    if (!CollectionUtils.isEmpty(socialSecurityList)) {
                        List<EduSocialSecurityVO> cbVOList = Convert.toList(EduSocialSecurityVO.class, socialSecurityList);
                        for (EduSocialSecurityVO eduSocialSecurityVO : cbVOList) {
                            if ("1".equalsIgnoreCase(eduSocialSecurityVO.getAac008())) {
                                if ("1".equalsIgnoreCase(eduSocialSecurityVO.getAac031())) {
                                    eduSocialSecurityVO.setStatus("1");
                                    eduSocialSecurityVO.setStatusName("正常参保");
                                } else {
                                    eduSocialSecurityVO.setStatus("2");
                                    eduSocialSecurityVO.setStatusName("参保中断");
                                }
                            } else {
                                eduSocialSecurityVO.setStatus("3");
                                eduSocialSecurityVO.setStatusName("参保终止");
                            }
                        }

                        studentEnrollVO.setSbList(cbVOList);
                    }
                }
            }
            if(studentEnrollVO.getQyFlag()){
                //企业
                if (StringUtils.isNotBlank(gbEnroll.getCompanyId())) {
                    QueryWrapper<EduCompany> companyQueryWrapper = new QueryWrapper<>();
                    companyQueryWrapper.lambda().eq(EduCompany::getYear, year)
                            .eq(EduCompany::getCompanyId, gbEnroll.getCompanyId());
                    List<EduCompany> companyList = eduCompanyService.list(companyQueryWrapper);
                    if (!CollectionUtils.isEmpty(companyList)) {
                        List<CompanyVO> qyVOList = Convert.toList(CompanyVO.class, companyList);
                        studentEnrollVO.setQyList(qyVOList);
                    }
                }
            }
            if(studentEnrollVO.getJzzFlag()){
                //居住证
                if (StringUtils.isNotBlank(gbEnroll.getLivePlaceId())) {
                    QueryWrapper<EduLivePlace> livePlaceQueryWrapper = new QueryWrapper<>();
                    livePlaceQueryWrapper.lambda().eq(EduLivePlace::getYear, year)
                            .eq(EduLivePlace::getLivePlaceId, gbEnroll.getLivePlaceId()).orderByAsc(EduLivePlace::getSfzh);
                    List<EduLivePlace> livePlaceList = eduLivePlaceService.list(livePlaceQueryWrapper);
                    if (!CollectionUtils.isEmpty(livePlaceList)) {
                        List<LivePlaceVO> livePlaceVOList = Convert.toList(LivePlaceVO.class, livePlaceList);
                        studentEnrollVO.setJzzList(livePlaceVOList);
                    }
                }
            }
            if(studentEnrollVO.getXjFlag()){
                //学籍
                if (StringUtils.isNotBlank(gbEnroll.getStudentStatusId())) {
                    EduStudentStatus studentStatus = eduStudentStatusService.getById(gbEnroll.getStudentStatusId());
                    if (studentStatus != null) {
                        studentEnrollVO.setXjInfo(
                                Convert.convert(StudentStatusVO.class, studentStatus));
                    }

                }else{
                    QueryWrapper<EduStudentStatus> statusQueryWrapper=new QueryWrapper<>();
                    statusQueryWrapper.lambda().eq(EduStudentStatus::getYear, gbEnroll.getYear())
                            .eq(EduStudentStatus::getIdcard, gbEnroll.getIdcard());
                    List<EduStudentStatus> studentStatusList=eduStudentStatusService.list(statusQueryWrapper);
                    if(!CollectionUtils.isEmpty(studentStatusList)){
                        studentEnrollVO.setXjInfo(
                                Convert.convert(StudentStatusVO.class, studentStatusList.get(0)));
                    }
                }
            }
            if (studentEnrollVO.getFcFlag()) {
                //房产
                if (StringUtils.isNotBlank(gbEnroll.getHouseId())) {
                    EduHouse eduHouse = eduHouseService.getHouseById(gbEnroll.getHouseId());
                    //数据为空去查询历史表
                    if (ObjectUtils.isEmpty(eduHouse)){
                        EduhHouse eduhHouse = eduhHouseService.getById(gbEnroll.getHouseId());
                        if (eduhHouse != null && eduhHouse.getStatus().equals(BoolEnum.TRUE.getType()) && eduhHouse.getAuthStatus().equals(AuthStatusEnum.YES.getType())) {
                            //判断是否加密过
                            if(EduStatusTypeEnum.success.getType().equals(eduhHouse.getEncryptFlag())){
                                eduhHouseService.decrypt(eduhHouse);
                            }
                            studentEnrollVO.setFcInfo(
                                    Convert.convert(EduHouseVO.class, eduhHouse));
                        }
                    }
                    if (eduHouse != null && eduHouse.getStatus().equals(BoolEnum.TRUE.getType()) && eduHouse.getAuthStatus().equals(AuthStatusEnum.YES.getType())) {
                        studentEnrollVO.setFcInfo(
                                Convert.convert(EduHouseVO.class, eduHouse));
                    }
                }
            }
            if (studentEnrollVO.getHjFlag()) {
                //户籍
                if (StringUtils.isNotBlank(gbEnroll.getHouseholdId())) {
                    EduHousehold eduHousehold = eduHouseholdService.getHouseholdById(gbEnroll.getHouseholdId());
                    if (eduHousehold != null && eduHousehold.getStatus().equals(BoolEnum.TRUE.getType())) {
                        studentEnrollVO.setHjInfo(
                                Convert.convert(EduHouseholdVO.class, eduHousehold));
                    }
                }
            }

        }

        studentEnrollVO.setParamsVOList(formConfigVOList);

        //查询户籍信息

        boolean houseHoldFlag = false;
        if (SchoolNatureEnum.mzg.getType().equalsIgnoreCase(studentEnrollVO.getSchoolNature())) {
            studentEnrollVO.setHasHousehold(false);
            studentEnrollVO.setHasHouse(false);
            if (gbEnroll != null) {

                if ("A".equalsIgnoreCase(gbEnroll.getConfigName())) {
                    studentEnrollVO.setHasHousehold(true);
                    studentEnrollVO.setHasHouse(true);
                    studentEnrollVO.setRegisterDate(null);
                } else if ("B".equalsIgnoreCase(gbEnroll.getConfigName())) {
                    studentEnrollVO.setHasHousehold(true);
                    studentEnrollVO.setHasHouse(false);
                    studentEnrollVO.setRegisterDate(null);
                } else if ("C".equalsIgnoreCase(gbEnroll.getConfigName())) {
                    studentEnrollVO.setHasHousehold(false);
                    studentEnrollVO.setHasHouse(true);
                    houseHoldFlag = true;
                } else if ("特殊户口".equalsIgnoreCase(gbEnroll.getConfigName())) {
                    studentEnrollVO.setHasHousehold(true);
                    studentEnrollVO.setHasHouse(false);
                } else {
                    houseHoldFlag = true;

                }
            }
        } else if (SchoolNatureEnum.mb.getType().equalsIgnoreCase(studentEnrollVO.getSchoolNature())) {
            if (StringUtils.isBlank(studentEnrollVO.getHouseholdAddress())) {
                houseHoldFlag = true;
            }
            if (!BoolEnum.TRUE.getType().equalsIgnoreCase(studentEnrollVO.getFollowingFlag())) {
                houseHoldFlag = true;
            }
        }
        if (houseHoldFlag) {
            QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
            householdQueryWrapper.lambda().select(EduHousehold::getAddress).eq(EduHousehold::getIdcard, studentEnrollVO.getIdcard())
                    .eq(EduHousehold::getAreaCode, studentEnrollVO.getAreaCode())
                    .eq(EduHousehold::getYear, studentEnrollVO.getYear())
                    .eq(EduHousehold::getStatus, BoolEnum.TRUE.getType());
            List<EduHousehold> householdList = eduHouseholdService.list(householdQueryWrapper);
            if (!CollectionUtils.isEmpty(householdList)) {
                studentEnrollVO.setHasHousehold(true);
                studentEnrollVO.setFollowingFlag(BoolEnum.TRUE.getType());
                if (StringUtils.isBlank(studentEnrollVO.getHouseholdAddress())) {
                    studentEnrollVO.setHouseholdAddress(householdList.get(0).getAddress());
                }
            } else {
                studentEnrollVO.setHasHousehold(false);
            }
        }
        Integer thisYear = eduHelper.thisYear();
        Boolean desensitizeFlag = vo.getDesensitizeFlag();
        if (desensitizeFlag == null) {
            if (thisYear - studentEnrollVO.getYear() == 0) {
                EduOperationCacheQueryVO queryOpVO = new EduOperationCacheQueryVO();
                queryOpVO.setClassify("2");
                queryOpVO.setAreaCode(studentEnrollVO.getAreaCode());
                queryOpVO.setYear(thisYear);
                EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryOpVO);
                if (eduOperationCacheVO == null) {
                    throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
                }
                Map<String, EduOperationCacheDetailVO> operation = eduOperationCacheVO.getOperation();
                EduOperationCacheDetailVO shOperation = null;
                if (SchoolNatureEnum.mzg.getType().equalsIgnoreCase(studentEnrollVO.getSchoolNature())) {
                    shOperation = operation.get("YW016");//录用业务时间
                } else if (SchoolNatureEnum.mb.getType().equalsIgnoreCase(studentEnrollVO.getSchoolNature())) {
                    if ("1".equalsIgnoreCase(studentEnrollVO.getAspirationType())) {
                        //民办第一志愿
                        shOperation = operation.get("YW009");
                    } else if ("2".equalsIgnoreCase(studentEnrollVO.getAspirationType())) {
                        //民办第二志愿
                        shOperation = operation.get("YW013");
                    } else if ("3".equalsIgnoreCase(studentEnrollVO.getAspirationType())) {
                        //民办第三志愿
                        shOperation = operation.get("YW057");
                    }
                }
                if (shOperation != null) {
                    if (shOperation.isFlag() || "2".equalsIgnoreCase(shOperation.getType())) {
                        desensitizeFlag = true;
                    } else {
                        desensitizeFlag = false;
                    }
                } else {
                    desensitizeFlag = false;
                }

            } else {
                desensitizeFlag = true;
            }

        }
        if (desensitizeFlag) {
            if (!EnrollStatusFormalEnum.lq.getType().equalsIgnoreCase(studentEnrollVO.getEnrollStatus())) {
                //录取不脱敏 其他都脱敏
                EduDesensitizeUtil.desensitizeStudentEnroll(studentEnrollVO);
            }
        }
        return studentEnrollVO;
    }

    @Override
    public Boolean checkShLq(EnrollCheckShLqVO vo) {
        if (vo.getYear() == null) {
            throw new AppException("年度不能为空");
        }
        if (StringUtils.isBlank(vo.getOpType())) {
            throw new AppException("操作类型不能为空");
        }


        int year;
        year = eduHelper.thisYear();

        if (vo.getYear() < year) {
            return true;
        } else if (vo.getYear() > year) {
            return false;
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            throw new AppException("未找到用户所属行政区划,可能是未配置所属组织");
        }
        //EduEnrollPlan eduEnrollPlan = enrollPlanIntegration.getByYear(year);
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class,vo);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if (eduOperationCacheVO.getOperation() == null) {
            throw new AppException(year + "年度招生计划参数不存在");
        }
        Long current = DateUtil.currentSeconds();
        if ("0".equals(vo.getOpType())) {
            //公办
            String schoolId = vo.getSchoolId();
            if (StringUtils.isNotBlank(schoolId)) {
                schoolId = SessionUtil.getOrgId();
            }
            QueryWrapper<EduAuthSchool> authSchoolQueryWrapper = new QueryWrapper<>();
            authSchoolQueryWrapper.lambda().eq(EduAuthSchool::getSchoolId, schoolId)
                    .eq(EduAuthSchool::getYear, year);
            if (eduAuthSchoolService.count(authSchoolQueryWrapper) > 0) {
                //城区学校eduEnrollPlan  DataStartDate
                EduOperationCacheDetailVO detailVO = eduOperationCacheVO.getOperation().get("YW003");
                return detailVO.isFlag() || "2".equalsIgnoreCase(detailVO.getType());
            } else {
                //其他学校 DataStartDateOther
                EduOperationCacheDetailVO detailVO = eduOperationCacheVO.getOperation().get("YW020");
                return detailVO.isFlag() || "2".equalsIgnoreCase(detailVO.getType());
            }

        } else if ("1".equals(vo.getOpType())) {
            //民办1 PrivateDataStartDate
            EduOperationCacheDetailVO detailVO = eduOperationCacheVO.getOperation().get("YW007");
            return detailVO.isFlag() || "2".equalsIgnoreCase(detailVO.getType());
        } else if ("2".equals(vo.getOpType())) {
            //民转公 getMzgDataStartDate
            EduOperationCacheDetailVO detailVO = eduOperationCacheVO.getOperation().get("YW014");
            return detailVO.isFlag() || "2".equalsIgnoreCase(detailVO.getType());
        } else if ("3".equals(vo.getOpType())) {
            //民办2 getPrivateDataStartDate2
            EduOperationCacheDetailVO detailVO = eduOperationCacheVO.getOperation().get("YW011");
            return detailVO.isFlag() || "2".equalsIgnoreCase(detailVO.getType());
        } else if ("4".equals(vo.getOpType())) {
            //民办3
            EduOperationCacheDetailVO detailVO = eduOperationCacheVO.getOperation().get("YW055");
            return detailVO.isFlag() || "2".equalsIgnoreCase(detailVO.getType());
        } else {
            return true;
        }

    }
    @Override
    @OpApi(funcCode = "eduStudentEnroll0014", title = "义务教育报名一键退回到待审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0014",
            operationName = "义务教育报名一键退回到待审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void backAuth(EduStudentEnrollKeyVO vo) {
        EduStudentEnroll old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被退回");
        }

        if (AuthStatusEnum.NODO.getType().equals(old.getAuthStatus())) {
            throw new AppException("报名数据已是待审核状态");
        }
        if (old.getSerialNum() != null) {
            throw new AppException("已摇号数据不能退回到待审核");
        }
        if(StringUtils.isBlank(old.getAreaCode())){
            old.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class,old);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if (eduOperationCacheVO.getOperation() == null) {
            throw new AppException(old.getYear() + "年度招生计划参数不存在");
        }
        Long current = DateUtil.currentSeconds();
        if ("0".equals(old.getSchoolNature())) {
            // 公办
            if(!eduOperationCacheVO.getOperation().get("YW003").isFlag()){
                throw new AppException("公办审核录取时间未配置，请核对");
            }
            if (eduOperationCacheVO.getOperation().get("YW003").getBegTime() != null && eduOperationCacheVO.getOperation().get("YW010").getBegTime() != null) {
                Long start = eduOperationCacheVO.getOperation().get("YW003").getBegTime().getTime() / 1000;
                Long end = eduOperationCacheVO.getOperation().get("YW004").getEndTime().getTime() / 1000;
                if (current - start < 0 || current - end > 0) {
                    Long startOther =  eduOperationCacheVO.getOperation().get("YW020").getBegTime().getTime() / 1000;
                    Long endOther = eduOperationCacheVO.getOperation().get("YW021").getEndTime().getTime() / 1000;
                    if (current - startOther < 0 || current - endOther > 0) {
                        throw new AppException("只有公办审核和录取期间才能退回到待审核");
                    }
                }
            } else {
                if(eduOperationCacheVO.getOperation().get("YW010").isFlag()){
                    throw new AppException("只有公办审核和录取期间才能退回到待审核");
                }
            }

        } else if ("1".equals(old.getSchoolNature())) {
            // 民办
            if ("1".equals(old.getAspirationType())) {
                // 第一志愿
                if(eduOperationCacheVO.getOperation().get("YW007")!=null){
                    if(!eduOperationCacheVO.getOperation().get("YW007").isFlag()){
                        throw new AppException("只有在民办第一志愿审核期间才能退回");
                    }
                }else{
                    throw new AppException("民办第一志愿审核期未配置，请核对");
                }
            } else if ("2".equals(old.getAspirationType())) {
                // 第二志愿
                if(eduOperationCacheVO.getOperation().get("YW011")!=null) {
                    if (!eduOperationCacheVO.getOperation().get("YW011").isFlag()) {
                        throw new AppException("只有在民办第二志愿审核期间才能退回");
                    }
                }else {
                    throw new AppException("民办第二志愿审核期未配置，请核对");
                }
            }else if ("3".equals(old.getAspirationType())) {
                // 第三志愿
                if(eduOperationCacheVO.getOperation().get("YW055")!=null) {
                    if (!eduOperationCacheVO.getOperation().get("YW055").isFlag()) {
                        throw new AppException("只有在民办第三志愿审核期间才能退回");
                    }
                }else {
                    throw new AppException("民办第三志愿审核期未配置，请核对");
                }
            }
        } else if ("2".equals(old.getSchoolNature())) {
            // 民转公
            if(eduOperationCacheVO.getOperation().get("YW014")!=null) {
                if (!eduOperationCacheVO.getOperation().get("YW014").isFlag()) {
                    throw new AppException("只有在民转公审核期间才能退回");
                }
            }else {
                throw new AppException("民转公审核期未配置，请核对");
            }
        }

        if (EnrollStatusFormalEnum.ywblq.getType().equals(old.getEnrollStatus()) || EnrollStatusFormalEnum.xtblq.getType().equals(old.getEnrollStatus())) {
            //从不录取退回到待审核，需要判断其他学校是否审核录取
            List<String> enrollStatusList = new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(EduStudentEnroll::getYear, old.getYear())
                    .eq(EduStudentEnroll::getIdcard, old.getIdcard())
                    .in(EduStudentEnroll::getEnrollStatus, enrollStatusList)
                    .ne(EduStudentEnroll::getStudentEnrollId, old.getStudentEnrollId());
            if (eduStudentEnrollService.count(queryWrapper) > 0) {
                throw new AppException("因其他学校已审核或录取，这个学校不能从不录取退回到待审核");
            }
        }


        old.setAuthStatus(AuthStatusEnum.NODO.getType());
        old.setAuthRemarks(null);
        old.setAuthTime(null);
        old.setAuthUserId(null);
        old.setAdmitFlag(null);
        old.setAdmitTime(null);
        old.setAdmitRemarks(null);
        old.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
        eduStudentEnrollService.updateById(old);
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0015", title = "义务教育报名退回（民办依托公办）", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0015",
            operationName = "义务教育报名退回（民办依托公办）",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywApplyBack(EduStudentEnrollKeyVO vo) {
        EduStudentEnroll studentEnroll = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (!StringUtils.equals(studentEnroll.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员已审核，不允许退回");
        }
        int year = eduHelper.thisYear();
        if(studentEnroll.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(studentEnroll.getAreaCode());
        queryVO.setYear(studentEnroll.getYear());
        EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
        Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();
        EduOperationCacheDetailVO bmOperation=operation.get("YW002");//报名时间
        EduOperationCacheDetailVO bbOperation=operation.get("YW022");//补报时间
        EduOperationCacheDetailVO qbOperation=operation.get("YW010");//抢报时间
        //判断是否报名业务期
        boolean bmFlag = bmOperation==null?false:bmOperation.isFlag();
        //判断是否补报业务期
        boolean bbFlag = bbOperation==null?false:bbOperation.isFlag();
        //判断是否空额抢报业务期
        boolean qbFlag = qbOperation==null?false:qbOperation.isFlag();
        if(!bmFlag&&!bbFlag&&!qbFlag){
            throw new AppException("报名时间已过不能撤销");
        }
        if(bbFlag&&!"1".equalsIgnoreCase(studentEnroll.getBbFlag())){
            throw new AppException("报名时间已过不能撤销");
        }
        if(qbFlag&&!"1".equalsIgnoreCase(studentEnroll.getSpareRegisterFlag())){
            throw new AppException("报名时间已过不能撤销");
        }
        if (bmFlag) {
            if ("1".equals(studentEnroll.getSchoolNature())) {
                throw new AppException("民办不能单独退回，回退公办学校时会同步退回民办学校");
            }
            if ("2".equals(studentEnroll.getSchoolNature())) {
                throw new AppException("公参民转公不能单独退回，回退公办学校时会同步退回公参民转公学校");
            }
        }
        if (SchoolNatureEnum.gb.getType().equals(studentEnroll.getSchoolNature())) {
            if (!BoolEnum.TRUE.getType().equals(studentEnroll.getBbFlag()) && !BoolEnum.TRUE.getType().equals(studentEnroll.getSpareRegisterFlag())) {
                QueryWrapper<EduStudentEnroll> shlqQuery = new QueryWrapper<>();
                shlqQuery.lambda().select(EduStudentEnroll::getStudentEnrollId)
                        .eq(EduStudentEnroll::getIdcard, studentEnroll.getIdcard())
                        .eq(EduStudentEnroll::getYear, studentEnroll.getYear())
                        .ne(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType());
                if (eduStudentEnrollService.count(shlqQuery) > 0) {
                    throw new AppException("已有学校操作审核或录取，不能退回，只有所有报名学校都是待审核才能进行退回操作");
                }
                //查看民办情况，有的话一起退回
                QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().select(EduStudentEnroll::getStudentEnrollId, EduStudentEnroll::getAuthStatus)
                        .eq(EduStudentEnroll::getParentId, vo.getStudentEnrollId());
                List<EduStudentEnroll> mbList = eduStudentEnrollService.list(queryWrapper);
                if (!CollectionUtils.isEmpty(mbList)) {
                    for (EduStudentEnroll eduStudentEnroll : mbList) {
                        if (!StringUtils.equals(eduStudentEnroll.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
                            throw new AppException("当前人员有学校已审核，请学生家长先联系审核学校处理后再做退回");
                        }
                        eduStudentEnrollService.removeById(eduStudentEnroll.getStudentEnrollId());
                    }
                }
            }
        }

        eduStudentEnrollService.removeById(vo.getStudentEnrollId());
        LambdaQueryWrapper<EduStudentEnrollPre> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.select(EduStudentEnrollPre::getStudentEnrollPreId).eq(EduStudentEnrollPre::getYear,studentEnroll.getYear())
                .eq(EduStudentEnrollPre::getIdcard,studentEnroll.getIdcard());
        List<EduStudentEnrollPre> preList=eduStudentEnrollPreService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(preList)){
            for(EduStudentEnrollPre pre:preList){
                eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
            }
        }
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getMotherIdcard());
        String bmKey = EduCache.EDU_ENROLL_ZS + studentEnroll.getIdcard();
        redisHelper.del(bmKey);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0064", title = "义务教育报名撤销（民办公办单独）", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0064",
            operationName = "义务教育报名撤销（民办公办单独）",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywApplyBackDg(EduStudentEnrollKeyVO vo) {
        EduStudentEnroll studentEnroll = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (!StringUtils.equals(studentEnroll.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员已审核，不允许退回");
        }
        eduStudentEnrollService.removeById(vo.getStudentEnrollId());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getMotherIdcard());
        String bmKey = EduCache.EDU_ENROLL_ZS + studentEnroll.getIdcard();
        redisHelper.del(bmKey);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0063", title = "家长端义务教育报名撤销", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0063",
            operationName = "家长端义务教育报名撤销",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywApplyBackApp(EduStudentEnrollKeyVO vo) {

        EduStudentEnroll studentEnroll = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (!StringUtils.equals(studentEnroll.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
            throw new AppException("当前人员已审核，不允许退回");
        }
        int year = eduHelper.thisYear();
        if(studentEnroll.getYear()<year){
            throw new AppException("历史数据不能操作");
        }
        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(studentEnroll.getAreaCode());
        queryVO.setYear(studentEnroll.getYear());
        EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
        Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();
        EduOperationCacheDetailVO bmOperation=operation.get("YW002");//报名时间
        EduOperationCacheDetailVO bbOperation=operation.get("YW022");//补报时间
        EduOperationCacheDetailVO qbOperation=operation.get("YW010");//抢报时间
        //判断是否报名业务期
        boolean bmFlag = bmOperation==null?false:bmOperation.isFlag();
        //判断是否补报业务期
        boolean bbFlag = bbOperation==null?false:bbOperation.isFlag();
        //判断是否空额抢报业务期
        boolean qbFlag = qbOperation==null?false:qbOperation.isFlag();
        if(!bmFlag&&!bbFlag&&!qbFlag){
            throw new AppException("报名时间已过不能撤销");
        }
        if(bbFlag&&!"1".equalsIgnoreCase(studentEnroll.getBbFlag())){
            throw new AppException("报名时间已过不能撤销");
        }
        if(qbFlag&&!"1".equalsIgnoreCase(studentEnroll.getSpareRegisterFlag())){
            throw new AppException("报名时间已过不能撤销");
        }

        if (bmFlag){
            if ("1".equals(studentEnroll.getSchoolNature())) {
                throw new AppException("民办不能单独退回，回退公办学校时会同步退回民办学校");
            }
            if ("2".equals(studentEnroll.getSchoolNature())) {
                throw new AppException("公参民转公不能单独退回，回退公办学校时会同步退回公参民转公学校");
            }
            if (SchoolNatureEnum.gb.getType().equals(studentEnroll.getSchoolNature())) {
                if (!BoolEnum.TRUE.getType().equals(studentEnroll.getBbFlag()) && !BoolEnum.TRUE.getType().equals(studentEnroll.getSpareRegisterFlag())) {
                    QueryWrapper<EduStudentEnroll> shlqQuery = new QueryWrapper<>();
                    shlqQuery.lambda().select(EduStudentEnroll::getStudentEnrollId)
                            .eq(EduStudentEnroll::getIdcard, studentEnroll.getIdcard())
                            .eq(EduStudentEnroll::getYear, studentEnroll.getYear())
                            .ne(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType());
                    if (eduStudentEnrollService.count(shlqQuery) > 0) {
                        throw new AppException("已有学校操作审核或录取，不能退回，只有所有报名学校都是待审核才能进行退回操作");
                    }
                    //查看民办情况，有的话一起退回
                    QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().select(EduStudentEnroll::getStudentEnrollId, EduStudentEnroll::getAuthStatus)
                            .eq(EduStudentEnroll::getParentId, vo.getStudentEnrollId());
                    List<EduStudentEnroll> mbList = eduStudentEnrollService.list(queryWrapper);
                    if (!CollectionUtils.isEmpty(mbList)) {
                        for (EduStudentEnroll eduStudentEnroll : mbList) {
                            if (!StringUtils.equals(eduStudentEnroll.getAuthStatus(), AuthStatusEnum.NODO.getType())) {
                                throw new AppException("当前人员有学校已审核，请学生家长先联系审核学校处理后再做退回");
                            }
                            eduStudentEnrollService.removeById(eduStudentEnroll.getStudentEnrollId());
                        }
                    }
                }
            }
        }
        LambdaQueryWrapper<EduStudentEnrollPre> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.select(EduStudentEnrollPre::getStudentEnrollPreId).eq(EduStudentEnrollPre::getYear,studentEnroll.getYear())
                .eq(EduStudentEnrollPre::getIdcard,studentEnroll.getIdcard());
        List<EduStudentEnrollPre> preList=eduStudentEnrollPreService.list(queryWrapper);
        if(!CollectionUtils.isEmpty(preList)){
            for(EduStudentEnrollPre pre:preList){
                eduEnrollClearCacheHelper.clearCachePreBefore(pre.getStudentEnrollPreId());
            }
        }
        eduStudentEnrollService.removeById(vo.getStudentEnrollId());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(studentEnroll.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(studentEnroll.getMotherIdcard());
        String bmKey = EduCache.EDU_ENROLL_ZS + studentEnroll.getIdcard();
        redisHelper.del(bmKey);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0016", title = "义务教育报名修改报名状态", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0016",
            operationName = "义务教育报名修改报名状态",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void updateEnrollStatus(UpdateEnrollStatusVO vo) {
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getEnrollStatus())) {
            throw new AppException("报名状态不能为空");
        }
        EduStudentEnroll old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被退回");
        }
        if (old.getEnrollStatus().equals(vo.getEnrollStatus())) {
            throw new AppException("报名状态和数据库中一致，请刷新后再操作");
        }
        boolean gbhfFlag = false;
        EduStudentEnroll gb = null;
        if (EnrollStatusFormalEnum.xtblq.getType().equalsIgnoreCase(vo.getEnrollStatus()) && !SchoolNatureEnum.gb.getType().equalsIgnoreCase(old.getSchoolNature())) {
            //民办
            if (StringUtils.isBlank(vo.getMbTcType())) {
                throw new AppException("请选择退出类型");
            }
            if (MbTcTypeEnum.fhgb.getType().equalsIgnoreCase(vo.getMbTcType())) {
                if (StringUtils.isNotBlank(old.getParentId())) {
                    gb = eduStudentEnrollService.getById(old.getParentId());
                    if (EnrollStatusFormalEnum.dsh.getType().equalsIgnoreCase(gb.getEnrollStatus())
                            || EnrollStatusFormalEnum.dlq.getType().equalsIgnoreCase(gb.getEnrollStatus())
                            || EnrollStatusFormalEnum.lq.getType().equalsIgnoreCase(gb.getEnrollStatus())) {
                        throw new AppException("公办学校状态已恢复，只需退出民办即可");
                    }
                    gb.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
                    gb.setAuthStatus(AuthStatusEnum.NODO.getType());
                    gb.setAdmitFlag(null);
                    gb.setAdmitTime(null);
                    gb.setAuthTime(null);
                    gb.setAuthRemarks("因民办退出录取返回公办学校");
                    gb.setAdmitRemarks("");
                    eduStudentEnrollService.updateById(gb);
                    gbhfFlag = true;
                }
            }
        }
        old.setEnrollStatus(vo.getEnrollStatus());
        eduStudentEnrollService.updateById(old);

        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getMotherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnrollPre(old.getMotherIdcard());
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0017", title = "义务教育报名人员查询(根据身份证)", funcType = FuncTypeEnum.query)
    public List<EduStudentEnrollVO> getYwApplyInfoByIdcard(EduStudentEnrollQueryVO vo) {
        if(StringUtils.isBlank(vo.getIdcard())){
            throw new AppException("身份证不能为空");
        }
        int year = eduHelper.thisYear();

        String schoolId = vo.getSchoolId();
        if (StringUtils.isBlank(schoolId)) {
            schoolId = SessionUtil.getSessionInfo().getOrgId();
        }
        QueryWrapper<EduStudentEnroll> studentEnrollQueryWrapper = new QueryWrapper<>();
        studentEnrollQueryWrapper
                .lambda()
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.dsh.getType())
                .eq(!ObjectUtils.isEmpty(vo.getYear()), EduStudentEnroll::getYear, year)
                .eq(EduStudentEnroll::getIdcard,
                        vo.getIdcard())
                .eq(EduStudentEnroll::getSchoolId, schoolId);
        List<EduStudentEnroll> list = eduStudentEnrollService.list(studentEnrollQueryWrapper);
        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
           throw new AppException("该人员未在本校报名，请让家长在我的报名记录中核对报名的公办学校");
        }
        // 不为空则获取分页结果
        List<EduStudentEnrollVO> resultList = Convert.toList(EduStudentEnrollVO.class, list);
        return resultList;
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0018", title = "义务教育报名信息导出", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void exportYwApplyInfo(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO=excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum=1;
        setDataexportYwApplyInfo(excelModelVO,null,destFilePath,vo,pageNum);
        String fileName=vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }

    }
    private void setDataexportYwApplyInfo(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduStudentEnrollQueryVO vo, int pageNum){
        vo.setPageNum(pageNum);
        vo.setPageSize(1000);
        boolean closeFlag=false;
        try {
            PageInfo<EduStudentEnrollVO> pageInfo= getYwApplyList(vo);
            String total=String.valueOf(pageInfo.getTotal());
            List<Object> list=new ArrayList<>();
            if(!CollectionUtils.isEmpty(pageInfo.getList())){
                for(EduStudentEnrollVO eduStudentEnrollVO:pageInfo.getList()){
                    list.add(eduStudentEnrollVO);
                }
            }
            if(pageNum==1){
                if(excelWriter==null){
                    excelWriter=excelCommonHelper.createExcelWriter(excelModelVO,destFilePath,Integer.parseInt(total));
                }
                excelCommonHelper.writeBean(excelWriter,list);
            }else{
                excelCommonHelper.writeBean(excelWriter,list);
            }
            if(pageInfo.isHasNextPage()){
                pageNum=pageNum+1;
                setDataexportYwApplyInfo(excelModelVO,excelWriter,destFilePath,vo,pageNum);
            }else{
                closeFlag=true;
            }
        }catch (AppException appEx){
            throw appEx;
        }catch (Exception e){
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        }finally {
            if(closeFlag&&excelWriter!=null){
                excelWriter.close();
            }
        }
    }

    @Override
    public PageInfo<EduStudentEnrollVO> getYwApplyList(EduStudentEnrollQueryVO vo) {
        if (StringUtils.isBlank(vo.getSchoolId())) {
            String orgId=SessionUtil.getOrgId();
            if(StringUtils.isNotBlank(orgId)) {
                EduSchoolVO school = eduSchoolService.getDetail(orgId);
                if (school != null) {
                    vo.setSchoolId(orgId);
                    if(StringUtils.isBlank(vo.getAreaCode())){
                        vo.setAreaCode(school.getAreaCode());
                    }
                }
            }
        }else{
            EduSchoolVO eduSchoolVO = eduSchoolService.getDetail(vo.getSchoolId());
            if(eduSchoolVO==null){
                vo.setAreaCode(SessionUtil.getAreaCode());
            }else {
                vo.setAreaCode(eduSchoolVO.getAreaCode());
            }

        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getAreaCode());
        }
        if (vo.getYear() == null) {
            throw new AppException("查询年度不能空");
        }
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setYear(vo.getYear());
        checkShLqVO.setOpType(vo.getOpType());
        checkShLqVO.setSchoolId(vo.getSchoolId());
        Boolean checkFlag = checkShLq(checkShLqVO);
        if (!checkFlag) {
            throw new AppException("本年度招生审核工作尚未开始");
        }

        if (!CollectionUtils.isEmpty(vo.getOrderVOList())) {
            String orderBy = "";
            for (OrderVO orderVO : vo.getOrderVOList()) {
                if (StringUtils.isNotBlank(orderVO.getOrder()) && StringUtils.isNotBlank(orderVO.getProperty())) {
                    orderBy = orderBy + ",";
                    if (orderVO.getProperty().equals("registerDate")) {
                        orderBy = orderBy + "a.";
                    } else if (orderVO.getProperty().equals("qysj")) {
                        orderBy = orderBy + "a.";
                    } else {
                        orderBy = orderBy + "a.";
                    }
                    orderBy = orderBy + StrUtil.toUnderlineCase(orderVO.getProperty()) + " " + orderVO.getOrder();
                }
            }
            vo.setOrderBy(orderBy);

        }
        List<EduStudentEnrollVO> list;
        Boolean queryHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),STUDENT_ENROLL_TABLE);
        if (!queryHistoryFlag) {
            // 开启分页
            if (vo.getPageNum() != null && vo.getPageSize() != null) {
                PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            }
             list = eduStudentEnrollService.getYwApplyList(vo);
        } else {
            Boolean encryptFlag = eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), STUDENT_ENROLL_TABLE);
            if (encryptFlag) {
                eduStudentEnrollService.queryEncrypt(vo);
            }
            // 开启分页
            if (vo.getPageNum() != null && vo.getPageSize() != null) {
                PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
            }
            list = eduhStudentEnrollService.getYwApplyListYq(vo);
            //解密
            for (EduStudentEnrollVO studentEnrollVO : list) {
                if ("1".equals(studentEnrollVO.getEncryptFlag())) {
                    eduStudentEnrollService.decrypt(studentEnrollVO);
                }
            }
        }

        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        Boolean desensitizeFlag = vo.getDesensitizeFlag();

        // 不为空则获取分页结果
        PageInfo<EduStudentEnrollVO> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduStudentEnrollVO> resultList = pageInfo.getList();
        dictHelper.valueToName(resultList, Arrays.asList(EduYwEnrollDictEnum.values()));
        Map<String, EduArea> areaMap =
                eduAreaService.list().stream()
                        .collect(Collectors.toMap(EduArea::getAreaCode, a -> a, (k1, k2) -> k1));
        boolean flag = false;
        String cqSchool = "all";//commonIntegration.getValueByKey("cq_school");
        Map<String, EduStudentEnroll> map = new HashMap<>();

        if ("2".equalsIgnoreCase(vo.getOpType()) && StringUtils.isNotBlank(cqSchool)) {
            // 获取公办报名学校和类别 民转公处理
            List<String> idList = resultList.stream().map(EduStudentEnrollVO::getParentId).collect(Collectors.toList());
            List<EduStudentEnroll> eduStudentEnrollList;
            if (!queryHistoryFlag){
                QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().select(EduStudentEnroll::getIdcard, EduStudentEnroll::getSchoolId, EduStudentEnroll::getConfigName)
                        .in(EduStudentEnroll::getStudentEnrollId, idList);
                if (!"all".equals(cqSchool)) {
                    List<String> schoolIdList = Arrays.stream(cqSchool.split(",")).map(s -> s).collect(Collectors.toList());
                    queryWrapper.lambda().in(EduStudentEnroll::getSchoolId, schoolIdList);
                }
                eduStudentEnrollList = eduStudentEnrollService.list(queryWrapper);
            }else {
                QueryWrapper<EduhStudentEnroll> eduhStudentEnrollQueryWrapper = new QueryWrapper<>();
                eduhStudentEnrollQueryWrapper.lambda().select(EduhStudentEnroll::getIdcard, EduhStudentEnroll::getSchoolId, EduhStudentEnroll::getConfigName)
                        .in(EduhStudentEnroll::getStudentEnrollId, idList);
                if (!"all".equals(cqSchool)) {
                    List<String> schoolIdList = Arrays.stream(cqSchool.split(",")).map(s -> s).collect(Collectors.toList());
                    eduhStudentEnrollQueryWrapper.lambda().in(EduhStudentEnroll::getSchoolId, schoolIdList);
                }
                List<EduhStudentEnroll> eduhStudentEnrollList = eduhStudentEnrollService.list(eduhStudentEnrollQueryWrapper);

                eduStudentEnrollList = Convert.toList(EduStudentEnroll.class, eduhStudentEnrollList);
            }
            if (!CollectionUtils.isEmpty(eduStudentEnrollList)) {
                map = eduStudentEnrollList.stream().collect(Collectors.toMap(EduStudentEnroll::getIdcard, a -> a, (k1, k2) -> k1));
            }
        }
        //获取报名id
        List<String> enrollIdList = resultList.stream().map(EduStudentEnrollVO::getStudentEnrollId).distinct().collect(Collectors.toList());
        List<String> authStatusList = new ArrayList<>();
        authStatusList.add(AuthStatusEnum.NODO.getType());
        authStatusList.add(AuthStatusEnum.YES.getType());
        QueryWrapper<EduStudentEnrollInvalid> invalidQueryWrapper = new QueryWrapper<>();
        invalidQueryWrapper.lambda()
                .select(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus)
                .in(EduStudentEnrollInvalid::getStudentEnrollId, enrollIdList)
                .in(EduStudentEnrollInvalid::getAuthStatus, authStatusList);
        List<EduStudentEnrollInvalid> invalidList = eduStudentEnrollInvalidService.list(invalidQueryWrapper);
        Map<String, String> collectMap =new HashMap<>();
        if(!CollectionUtils.isEmpty(invalidList)){
            collectMap=invalidList.stream().collect(Collectors.toMap(EduStudentEnrollInvalid::getStudentEnrollId, EduStudentEnrollInvalid::getAuthStatus));
        }
        //获取学生证件号码
        List<String> idcardList = resultList.stream().map(EduStudentEnrollVO::getIdcard).distinct().collect(Collectors.toList());
        Map<String, String> householdMap = new HashMap<>();
        //查询户籍信息
        Boolean householdHistoryFlag = eduDataTaskDetailService.verifyQueryHistory(vo.getYear(),EDU_HOUSEHOLD);
        if (!householdHistoryFlag) {
            QueryWrapper<EduHousehold> householdQueryWrapper = new QueryWrapper<>();
            householdQueryWrapper.lambda().in(EduHousehold::getIdcard, idcardList)
                    .eq(EduHousehold::getYear, vo.getYear())
                    .eq(EduHousehold::getStatus, BoolEnum.TRUE.getType());
            List<EduHousehold> householdList = eduHouseholdService.list(householdQueryWrapper);
            if (!CollectionUtils.isEmpty(householdList)) {
                householdMap = householdList.stream().collect(Collectors.toMap(EduHousehold::getIdcard, EduHousehold::getAddress, (k1, k2) -> k1));
            }
        }else {
            Boolean encryptFlag = eduDataTaskDetailService.verifyHistoryEncrypt(vo.getYear(), EDU_HOUSEHOLD);
            QueryWrapper<EduhHousehold> eduhHouseholdQueryWrapper = new QueryWrapper<>();
            eduhHouseholdQueryWrapper.lambda()
                    .eq(EduhHousehold::getYear, vo.getYear())
                    .eq(EduhHousehold::getStatus, BoolEnum.TRUE.getType());
            if (encryptFlag) {
                //加密身份证
                ArrayList<String> idcardListEncrypt = new ArrayList<>();
                for (String idCard : idcardList) {
                    idcardListEncrypt.add(CommonSecureUtil.sm4Encrypt(idCard));
                }
                eduhHouseholdQueryWrapper.lambda().in(EduhHousehold::getIdcard, idcardListEncrypt);
            } else {
                eduhHouseholdQueryWrapper.lambda().in(EduhHousehold::getIdcard, idcardList);
            }
            List<EduhHousehold> eduhHouseholdList = eduhHouseholdService.list(eduhHouseholdQueryWrapper);
            //解密
            for (EduhHousehold eduhHousehold : eduhHouseholdList) {
                if ("1".equals(eduhHousehold.getEncryptFlag())) {
                    if (StringUtils.isNotBlank(eduhHousehold.getIdcard())) {
                        eduhHousehold.setIdcard(CommonSecureUtil.sm4Decrypt(eduhHousehold.getIdcard()));
                    }
                    if (StringUtils.isNotBlank(eduhHousehold.getFullName())) {
                        eduhHousehold.setFullName(CommonSecureUtil.sm4Decrypt(eduhHousehold.getFullName()));
                    }
                    if (StringUtils.isNotBlank(eduhHousehold.getBeforeName())) {
                        eduhHousehold.setBeforeName(CommonSecureUtil.sm4Decrypt(eduhHousehold.getBeforeName()));
                    }
                    if (StringUtils.isNotBlank(eduhHousehold.getAddress())) {
                        eduhHousehold.setAddress(CommonSecureUtil.sm4Decrypt(eduhHousehold.getAddress()));
                    }
                    if (StringUtils.isNotBlank(eduhHousehold.getHouseholdPlace())) {
                        eduhHousehold.setHouseholdPlace(CommonSecureUtil.sm4Decrypt(eduhHousehold.getHouseholdPlace()));
                    }
                    if (StringUtils.isNotBlank(eduhHousehold.getHouseholder())) {
                        eduhHousehold.setHouseholder(CommonSecureUtil.sm4Decrypt(eduhHousehold.getHouseholder()));
                    }
                    if (StringUtils.isNotBlank(eduhHousehold.getHouseholderIdcard())) {
                        eduhHousehold.setHouseholderIdcard(CommonSecureUtil.sm4Decrypt(eduhHousehold.getHouseholderIdcard()));
                    }
                }
                householdMap = eduhHouseholdList.stream().collect(Collectors.toMap(EduhHousehold::getIdcard, EduhHousehold::getAddress, (k1, k2) -> k1));
            }
        }
        Integer year = eduHelper.thisYear();
        if (desensitizeFlag == null) {
            if (!"0".equalsIgnoreCase(vo.getOpType())) {
                if (year - vo.getYear() == 0) {
                    EduOperationCacheQueryVO queryVO = new EduOperationCacheQueryVO();
                    queryVO.setClassify("2");
                    queryVO.setAreaCode(vo.getAreaCode());
                    queryVO.setYear(year);
                    EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryVO);
                    if (eduOperationCacheVO == null) {
                        throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
                    }
                    Map<String, EduOperationCacheDetailVO> operation = eduOperationCacheVO.getOperation();
                    EduOperationCacheDetailVO shOperation = null;
                    if ("1".equalsIgnoreCase(vo.getOpType())) {
                        //民办第一志愿
                        shOperation = operation.get("YW009");
                    } else if ("2".equalsIgnoreCase(vo.getOpType())) {
                        //民转公
                        shOperation = operation.get("YW016");//录用业务时间
                    } else if ("3".equalsIgnoreCase(vo.getOpType())) {
                        //民办第二志愿
                        shOperation = operation.get("YW013");
                    } else if ("4".equalsIgnoreCase(vo.getOpType())) {
                        //民办第三志愿
                        shOperation = operation.get("YW057");
                    }
                    if (shOperation != null) {
                        if ("2".equalsIgnoreCase(shOperation.getType())) {
                            desensitizeFlag = true;
                        } else {
                            desensitizeFlag = false;
                        }
                    } else {
                        desensitizeFlag = false;
                    }

                } else {
                    desensitizeFlag = true;
                }
            } else {
                desensitizeFlag = false;
            }
        }
        for (EduStudentEnrollVO studentEnroll : resultList) {
            if (SchoolNatureEnum.mzg.getType().equalsIgnoreCase(studentEnroll.getSchoolNature())) {
                studentEnroll.setHasHousehold(false);
                studentEnroll.setHasHouse(false);
                EduStudentEnroll enroll = map.get(studentEnroll.getIdcard());
                if (enroll != null) {
                    studentEnroll.setGbConfigName(enroll.getConfigName());
                    studentEnroll.setGbSchoolName(enroll.getSchoolName());
                    if ("A".equalsIgnoreCase(enroll.getConfigName())) {
                        studentEnroll.setHasHousehold(true);
                        studentEnroll.setHasHouse(true);
                        studentEnroll.setRegisterDate(null);
                    } else if ("B".equalsIgnoreCase(enroll.getConfigName())) {
                        studentEnroll.setHasHousehold(true);
                        studentEnroll.setHasHouse(false);
                        studentEnroll.setRegisterDate(null);
                    } else if ("C".equalsIgnoreCase(enroll.getConfigName())) {
                        studentEnroll.setHasHousehold(false);
                        studentEnroll.setHasHouse(true);
                        if (householdMap.containsKey(studentEnroll.getIdcard())) {
                            studentEnroll.setHasHousehold(true);
                            if (StringUtils.isBlank(studentEnroll.getHouseholdAddress())) {
                                studentEnroll.setHouseholdAddress(householdMap.get(studentEnroll.getIdcard()));
                            }
                        } else {
                            studentEnroll.setHasHousehold(false);
                        }
                    } else if ("特殊户口".equalsIgnoreCase(enroll.getConfigName())) {
                        studentEnroll.setHasHousehold(true);
                        studentEnroll.setHasHouse(false);
                    } else {
                        if (householdMap.containsKey(studentEnroll.getIdcard())) {
                            studentEnroll.setHasHousehold(true);
                            if (StringUtils.isBlank(studentEnroll.getHouseholdAddress())) {
                                studentEnroll.setHouseholdAddress(householdMap.get(studentEnroll.getIdcard()));
                            }
                        } else {
                            studentEnroll.setHasHousehold(false);
                        }

                    }
                }
            } else if (SchoolNatureEnum.mb.getType().equalsIgnoreCase(studentEnroll.getSchoolNature())) {
                if (StringUtils.isBlank(studentEnroll.getHouseholdAddress())) {
                    studentEnroll.setHouseholdAddress(householdMap.get(studentEnroll.getIdcard()));
                }
                if (!BoolEnum.TRUE.getType().equalsIgnoreCase(studentEnroll.getFollowingFlag())) {
                    if (householdMap.containsKey(studentEnroll.getIdcard())) {
                        studentEnroll.setFollowingFlag(BoolEnum.TRUE.getType());
                    }
                }
            }
            studentEnroll.setDelStatus(collectMap.get(studentEnroll.getStudentEnrollId()));

            if (!flag && EnrollStatusFormalEnum.dlq.getType().equals(studentEnroll.getEnrollStatus())) {
                flag = true;
                studentEnroll.setFirstFlag(true);
            } else {
                studentEnroll.setFirstFlag(false);
            }
            //设置街道
            if (!ObjectUtils.isEmpty(areaMap.get(studentEnroll.getStreet()))) {
                studentEnroll.setStreetName(areaMap.get(studentEnroll.getStreet()).getAreaName());
            }
            if (StringUtils.isBlank(studentEnroll.getAdmitFlag())) {
                studentEnroll.setAdmitFlag("2");
                studentEnroll.setAdmitFlagName("待录取");
            } else {
                if (BoolEnum.TRUE.getType().equals(studentEnroll.getAdmitFlag())) {
                    studentEnroll.setAdmitFlagName("已录取");
                } else {
                    studentEnroll.setAdmitFlagName("不予录取");
                }
            }
            if (BoolEnum.TRUE.getType().equals(studentEnroll.getSpecialFlag())) {
                studentEnroll.setSpecialFlagName("是");
            } else {
                studentEnroll.setSpecialFlagName("否");
            }
            if (StringUtils.isNotBlank(studentEnroll.getEnrollStatus())) {
                EnrollStatusFormalEnum formalEnum = EnrollStatusFormalEnum.getByType(studentEnroll.getEnrollStatus());
                studentEnroll.setEnrollStatusName(formalEnum == null ? "未知状态" : formalEnum.getName());
            } else {
                studentEnroll.setEnrollStatus(EnrollStatusFormalEnum.dsh.getType());
                studentEnroll.setEnrollStatusName(EnrollStatusFormalEnum.dsh.getName());
            }
            studentEnroll.setFullNameTm(getFullName(studentEnroll.getFullName()));
            studentEnroll.setIdcardTm(getIdcard(studentEnroll.getIdcard()));
            if(studentEnroll.getSerialNum()!=null){
                studentEnroll.setSerialFlagName("是");
            }else{
                studentEnroll.setSerialFlagName("否");
            }
            if (desensitizeFlag) {
                if (!EnrollStatusFormalEnum.lq.getType().equalsIgnoreCase(studentEnroll.getEnrollStatus())) {
                    //录取不脱敏 其他都脱敏
                    EduDesensitizeUtil.desensitizeStudentEnroll(studentEnroll);
                }
            }
        }

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0020", title = "义务教育报名人数信息查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public StudentEnrollCntVO queryBmCnt(EduStudentEnrollQueryVO vo) {
        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(20);
        }
        if (vo.getYear() == null) {
            throw new AppException("请输入查询年份");
        }
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setYear(vo.getYear());
        checkShLqVO.setOpType(vo.getOpType());
        checkShLqVO.setSchoolId(vo.getSchoolId());
        Boolean flag = checkShLq(checkShLqVO);
        StudentEnrollCntVO retVO = new StudentEnrollCntVO();
        Integer zrs = 0;
        Integer dsh = 0;
        Integer dlq = 0;
        Integer ylq = 0;
        if (!flag) {
            retVO.setZrs(zrs);
            retVO.setDsh(dsh);
            retVO.setDlq(dlq);
            retVO.setYlq(ylq);
            retVO.setJhs(0);
            retVO.setLqFlag(false);
            return retVO;
        }

        QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.ywblq.getType());
        queryWrapper.lambda().select(EduStudentEnroll::getEnrollStatus)
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduStudentEnroll::getSchoolId, vo.getSchoolId())
                .eq(EduStudentEnroll::getYear, vo.getYear())
                .in(EduStudentEnroll::getEnrollStatus, enrollStatusList)
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()), EduStudentEnroll::getConfigTypeName, vo.getConfigTypeName())
                .eq(StringUtils.isNotBlank(vo.getConfigName()), EduStudentEnroll::getConfigTypeName, vo.getConfigName())
                .eq(StringUtils.isNotBlank(vo.getFollowingFlag()),EduStudentEnroll::getFollowingFlag,vo.getFollowingFlag());
        List<EduStudentEnroll> list = eduStudentEnrollService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            for (EduStudentEnroll enroll : list) {
                if (EnrollStatusFormalEnum.lq.getType().equals(enroll.getEnrollStatus())) {
                    ylq = ylq + 1;
                }
            }
        }
        queryWrapper.lambda().eq(StringUtils.isNotBlank(vo.getAspirationType()), EduStudentEnroll::getAspirationType, vo.getAspirationType());
        list = eduStudentEnrollService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(list)) {
            zrs = list.size();
            for (EduStudentEnroll enroll : list) {
                if (EnrollStatusFormalEnum.dsh.getType().equals(enroll.getEnrollStatus())) {
                    dsh = dsh + 1;
                }
                if (EnrollStatusFormalEnum.dlq.getType().equals(enroll.getEnrollStatus())) {
                    dlq = dlq + 1;
                }
            }

        }

        retVO.setZrs(zrs);
        retVO.setDsh(dsh);
        retVO.setDlq(dlq);
        retVO.setYlq(ylq);
        QueryWrapper<EduSchoolConfig> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment, EduSchoolConfig::getSerialNumEnd)
                .eq(StringUtils.isNotBlank(vo.getSchoolId()), EduSchoolConfig::getSchoolId, vo.getSchoolId())
                .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getYear, vo.getYear())
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()), EduSchoolConfig::getConfigTypeName, vo.getConfigTypeName());
        List<EduSchoolConfig> configList = eduSchoolConfigService.list(configQueryWrapper);
        int jhs = 0;
        if (!CollectionUtils.isEmpty(configList)) {
            for (EduSchoolConfig config : configList) {
                Integer count = config.getEnrolment() == null ? 0 : config.getEnrolment();
                jhs = jhs + count;
            }
        }
        int serialNumEnd = 0;
        if (StringUtils.isNotBlank(vo.getConfigTypeName())) {
            if (!CollectionUtils.isEmpty(configList)) {
                serialNumEnd = configList.get(0).getSerialNumEnd() == null ? 0 : configList.get(0).getSerialNumEnd();
            }
        }
        retVO.setSerialNumEnd(serialNumEnd);
        retVO.setJhs(jhs);
        if (jhs - ylq > 0) {
            retVO.setLqFlag(true);
        } else {
            retVO.setLqFlag(false);
        }
        return retVO;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0021", title = "义务教育民转公批量录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0021",
            operationName = "义务教育民转公批量录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void batchMzgAdmit(StudentEnrollBatchVO vo) {
        batchAdmit(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0022", title = "义务教育民办第一志愿批量录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0022",
            operationName = "义务教育民办第一志愿批量录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void batchAdmit(StudentEnrollBatchVO vo) {
        String schoolId = vo.getSchoolId();
        if(StringUtils.isBlank(schoolId)){
            schoolId=SessionUtil.getSessionInfo().getOrgId();
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        String reidsKey=batchAdmitKey+vo.getSchoolId();
        if(redisHelper.hasKey(reidsKey)){
            throw new AppException("系统正在执行中，请稍后！");
        }
        if(StringUtils.isBlank(vo.getConfigTypeName())){
            throw new AppException("报名类别不能为空");
        }
        int year = 0;
        year = eduHelper.thisYear();
        QueryWrapper<EduStudentEnroll> studentEnrollQueryWrapper = new QueryWrapper<>();
        studentEnrollQueryWrapper.lambda().eq(EduStudentEnroll::getSchoolId, schoolId)
                .eq(EduStudentEnroll::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduStudentEnroll::getYear,year)
                .eq(StringUtils.isNotBlank(vo.getAspirationType()),EduStudentEnroll::getAspirationType,vo.getAspirationType())
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()),EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.dlq.getType());
        List<EduStudentEnroll> studentEnrollList =
                eduStudentEnrollService.list(studentEnrollQueryWrapper);
        if(CollectionUtils.isEmpty(studentEnrollList)){
            throw new AppException("没有需要录取的人员");
        }
        studentEnrollQueryWrapper.lambda().isNotNull(EduStudentEnroll::getSerialNum);
        if(eduStudentEnrollService.count(studentEnrollQueryWrapper)>0){
            throw new AppException("摇号的数据，只能单个录取");
        }
        QueryWrapper<EduSchoolConfig> configQueryWrapper=new QueryWrapper<>();
        configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment, EduSchoolConfig::getSerialNumEnd)
                .eq(EduSchoolConfig::getSchoolId,schoolId)
                .eq(EduSchoolConfig::getAuthStatus,AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getStatus,BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getYear,year)
                .eq(EduSchoolConfig::getConfigTypeName,vo.getConfigTypeName());
        EduSchoolConfig eduSchoolConfig=eduSchoolConfigService.getOne(configQueryWrapper,false);
        if(eduSchoolConfig==null){
            throw new AppException("该报名类别未配置招生计划");
        }

        //摇号序号截止
        Integer serialNumEnd = eduSchoolConfig.getSerialNumEnd() == null ? 0 : eduSchoolConfig.getSerialNumEnd();
        //招生计划人数
        Integer enrolment=eduSchoolConfig.getEnrolment()==null?0:eduSchoolConfig.getEnrolment();

        QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper=new QueryWrapper<>();
        brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,year)
                .eq(EduEnrollmenBrochure::getSchoolId,schoolId);
        EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(brochureQueryWrapper,false);
        if(eduEnrollmenBrochure==null){
            throw new AppException("未找到招生方案信息");
        }
        EduOperationCacheQueryVO queryOpVO = new EduOperationCacheQueryVO();
        queryOpVO.setClassify("2");
        queryOpVO.setAreaCode(eduEnrollmenBrochure.getAreaCode());
        queryOpVO.setYear(eduEnrollmenBrochure.getYear());
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(queryOpVO);
        if (eduOperationCacheVO == null) {
            throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
        }

        Map<String, EduOperationCacheDetailVO> operation = eduOperationCacheVO.getOperation();
        if("1".equals(vo.getAspirationType())){
            if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                throw new AppException("第一志愿招生已停止，不能录取");
            }
            EduOperationCacheDetailVO detailVO = operation.get("YW009");
            if (!detailVO.isFlag()) {
                throw new AppException("未在第一志愿招生录取操作期内，请联系基教科处理");
            }
        }else if("2".equals(vo.getAspirationType())){
            if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
                throw new AppException("第二志愿招生已停止，不能录取");
            }
            EduOperationCacheDetailVO detailVO = operation.get("YW013");
            if (!detailVO.isFlag()) {
                throw new AppException("未在第二志愿招生录取操作期内，请联系基教科处理");
            }
        }else if("3".equals(vo.getAspirationType())){
            if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
                throw new AppException("第三志愿招生已停止，不能录取");
            }
            EduOperationCacheDetailVO detailVO = operation.get("YW057");
            if (!detailVO.isFlag()) {
                throw new AppException("未在第三志愿招生录取操作期内，请联系基教科处理");
            }
        }else if("4".equals(vo.getAspirationType())){
            if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())){
                throw new AppException("第四志愿招生已停止，不能录取");
            }
        }else{
            if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                throw new AppException("招生已停止，不能录取");
            }
        }

        //已录取人数
        QueryWrapper<EduStudentEnroll> lqQuery=new QueryWrapper<>();
        lqQuery.lambda().eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.lq.getType())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getAdmitFlag,BoolEnum.TRUE.getType())
                .eq(EduStudentEnroll::getSchoolId,schoolId)
                .eq(EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName());
        Long lqCount=eduStudentEnrollService.count(lqQuery);
        if ((studentEnrollList.size()+lqCount) > enrolment) {
            throw new AppException("该报名类别录取人数大于计划招生人数，请核对");
        }
        List<String> enrollStatusList=new ArrayList<>();

        enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        CommonVO commonVO = new CommonVO();
        commonVO.setParamKey("localLqDw");
        commonVO.setAreaCode(vo.getAreaCode());
        String localDw = commonIntegration.getValueByKeyAndArea(commonVO);
        if(StringUtils.isBlank(localDw)){
            throw new AppException("请先配置金华教育本地录取单位");
        }
        studentEnrollList.forEach(
                item -> {
                    EduStudentEnrollVO queryVO = Convert.convert(EduStudentEnrollVO.class, item);
                    EduDyjyQuerySyncVO eduDyjyQuerySyncVO = dyjyQuerySyncIntegration.querySyncInfo(queryVO);
                    if (StringUtils.isNotBlank(eduDyjyQuerySyncVO.getLqDw()) && !localDw.equals(eduDyjyQuerySyncVO.getLqDw())) {
                        throw new AppException("学生(" + item.getFullName() + ")已被" + eduDyjyQuerySyncVO.getLqDw() + "录取，请联系基教科处理");
                    }
                    item.setEnrollStatus(EnrollStatusFormalEnum.lq.getType());
                    item.setAdmitFlag(BoolEnum.TRUE.getType());
                    item.setAdmitTime(new Date());
                    item.setAdmitRemarks("报名人数未达计划数批量录取");
                    item.setAdmitUserId(SessionUtil.getSessionInfo().getUserId());

                    QueryWrapper<EduStudentEnroll> otherQuery=new QueryWrapper<>();
                    otherQuery.lambda().ne(EduStudentEnroll::getSchoolId,item.getSchoolId())
                            .eq(EduStudentEnroll::getIdcard,item.getIdcard())
                            .eq(EduStudentEnroll::getYear,item.getYear())
                            .in(EduStudentEnroll::getEnrollStatus,enrollStatusList);
                    List<EduStudentEnroll> otherList=eduStudentEnrollService.list(otherQuery);
                    if(!CollectionUtils.isEmpty(otherList)){
                        for(EduStudentEnroll enroll:otherList){
                            enroll.setEnrollStatus(EnrollStatusFormalEnum.xtblq.getType());
                            enroll.setAdmitFlag(BoolEnum.FALSE.getType());
                            enroll.setAdmitRemarks("因其他学校录取，系统自动设置为不录取");
                            if(enroll.getAuthStatus().equals(AuthStatusEnum.NODO.getType())){
                                enroll.setAuthStatus(AuthStatusEnum.NO.getType());
                                enroll.setAuthRemarks("因其他学校录取，系统自动设置为审核不通过");
                                enroll.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
                            }
                            enroll.setAdmitUserId(SessionUtil.getSessionInfo().getUserId());
                            eduStudentEnrollService.updateById(enroll);
                        }
                    }
                });
        try{
            redisHelper.set(reidsKey,1,600);
            eduStudentEnrollService.updateBatchById(studentEnrollList);
        }catch (Exception e){
            throw new AppException("保存数据异常"+e.getMessage());
        }finally {
            redisHelper.del(reidsKey);
        }
        studentEnrollList.forEach(item -> {
            eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getMotherIdcard());
        });
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0024", title = "义务教育民转公停止招生", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0024",
            operationName = "义务教育民转公停止招生",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMzgStop(StudentEnrollStopVO vo) {
        vo.setAspirationType("1");
        this.ywStop(vo);
    }

    private void ywStop(StudentEnrollStopVO vo) {
        if(StringUtils.isBlank(vo.getSchoolId())){
            vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        }
        String reidsKey=stopKey+vo.getSchoolId();
        if(redisHelper.hasKey(reidsKey)){
            throw new AppException("系统正在执行中，请稍后！");
        }

        int year = 0;
        year = eduHelper.thisYear();
        QueryWrapper<EduEnrollmenBrochure> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,year)
                .eq(EduEnrollmenBrochure::getSchoolId,vo.getSchoolId());
        EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(queryWrapper,false);
        if(eduEnrollmenBrochure==null){
            throw new AppException("未找到招生方案信息");
        }
        if(StringUtils.isBlank(vo.getAspirationType())){
            vo.setAspirationType("1");
        }
        EduSchool eduSchool=eduSchoolService.getById(SessionUtil.getSessionInfo().getOrgId());
        if("1".equals(eduSchool.getSchoolNature())){
            if(StringUtils.isBlank(vo.getAspirationType())){
                throw new AppException("民办需要传入志愿类型");
            }
            //民办
            if("1".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("第一志愿招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration(BoolEnum.TRUE.getType());
            }else if("2".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
                    throw new AppException("第二志愿招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration2(BoolEnum.TRUE.getType());
            }else if("3".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
                    throw new AppException("第三志愿招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration2(BoolEnum.TRUE.getType());
            }else if("4".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())){
                    throw new AppException("第四志愿招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration2(BoolEnum.TRUE.getType());
            }else{
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration(BoolEnum.TRUE.getType());
            }
        }else{
            if("1".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration(BoolEnum.TRUE.getType());
            }else if("2".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
                    throw new AppException("第二志愿招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration2(BoolEnum.TRUE.getType());
            }else if("3".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
                    throw new AppException("第三志愿招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration2(BoolEnum.TRUE.getType());
            }else if("4".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())){
                    throw new AppException("第四志愿招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration2(BoolEnum.TRUE.getType());
            }else{
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("招生已停止");
                }
                eduEnrollmenBrochure.setEndRegistration(BoolEnum.TRUE.getType());
            }
        }

        eduEnrollmenBrochureService.updateById(eduEnrollmenBrochure);
        //所有未录取的改成不录取
        List<String> dlqList=new ArrayList<>();
        dlqList.add(EnrollStatusFormalEnum.dlq.getType());
        dlqList.add(EnrollStatusFormalEnum.dsh.getType());
        QueryWrapper<EduStudentEnroll> studentEnrollQueryWrapper = new QueryWrapper<>();
        studentEnrollQueryWrapper.lambda().eq(EduStudentEnroll::getSchoolId, vo.getSchoolId())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getAspirationType,vo.getAspirationType())
                .in(EduStudentEnroll::getEnrollStatus,dlqList);

        List<EduStudentEnroll> studentEnrollList =
                eduStudentEnrollService.list(studentEnrollQueryWrapper);
        if (!CollectionUtils.isEmpty(studentEnrollList)){
            studentEnrollList.forEach(
                    item -> {
                        if(item.getAuthStatus().equals(AuthStatusEnum.NODO.getType())){
                            item.setAuthStatus(AuthStatusEnum.NO.getType());
                            item.setAuthTime(new Date());
                            item.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
                            item.setAuthRemarks("停止招生，批量改为审核不通过");
                        }
                        item.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
                        item.setAdmitFlag(BoolEnum.FALSE.getType());
                        item.setAdmitTime(new Date());
                        item.setAdmitRemarks("停止招生，批量改为不录取");
                    });
            try{
                redisHelper.set(reidsKey,1,600);
                eduStudentEnrollService.updateBatchById(studentEnrollList);
            }catch (Exception e){
                throw new AppException("保存数据异常"+e.getMessage());
            }finally {
                redisHelper.del(reidsKey);
            }
            studentEnrollList.forEach(item -> {
                eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getMotherIdcard());
            });
        }

    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0025", title = "获取义务教育民转公报名列表信息", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollVO> getYwMzgApplyInfo(EduStudentEnrollQueryVO vo) {
        vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        vo.setOpType("2");
        PageInfo<EduStudentEnrollVO> pageInfo= this.getYwApplyList(vo);
        return pageInfo;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0026", title = "义务教育民转公审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0026",
            operationName = "义务教育民转公审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMzgAudit(StudentEnrollSaveVO vo) {
        this.auth(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0027", title = "义务教育民转公单个录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0027",
            operationName = "义务教育民转公单个录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public StudentEnrollLqVO ywMzgApply(StudentEnrollSaveVO vo){
        return this.admit(vo);
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0029", title = "义务教育民办第一志愿报名摇号信息导出", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void exportYwMbApplyInfo(EduStudentEnrollQueryVO vo, HttpServletResponse response) {

        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO=excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum=1;
        setData(excelModelVO,null,destFilePath,vo,pageNum);
        String fileName=vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }
    }

    private void setData(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduStudentEnrollQueryVO vo, int pageNum){
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag = false;
        try {
            if(vo.getYear()==null){
                throw new AppException("招生年度不能为空");
            }
            QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper=new QueryWrapper<>();
            brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,vo.getYear())
                    .eq(EduEnrollmenBrochure::getSchoolId,SessionUtil.getSessionInfo().getOrgId());
            EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(brochureQueryWrapper,false);
            if(eduEnrollmenBrochure==null){
                throw new AppException("未找到学校招生方案信息");
            }
            EduSchool eduSchool=eduSchoolService.getById(SessionUtil.getSessionInfo().getOrgId());
            if("1".equals(eduSchool.getSchoolNature())){
                //民办
                if("1".equals(vo.getAspirationType())){
                    if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                        throw new AppException("第一志愿招生已停止，不能导出");
                    }
                }else if("2".equals(vo.getAspirationType())){
                    if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
                        throw new AppException("第二志愿招生已停止，不能导出");
                    }
                }else if("3".equals(vo.getAspirationType())){
                    if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
                        throw new AppException("第三志愿招生已停止，不能导出");
                    }
                }else if("4".equals(vo.getAspirationType())){
                    if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())){
                        throw new AppException("第四志愿招生已停止，不能导出");
                    }
                }else{
                    if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                        throw new AppException("招生已停止，不能导出");
                    }
                }
            }else{
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("招生已停止，不能导出");
                }
            }
            PageInfo<EduStudentEnrollVO> pageInfo= getYwApplyList(vo);
            String total=String.valueOf(pageInfo.getTotal());
            List<Map<String,Object>> list=new ArrayList<>();
            if(!CollectionUtils.isEmpty(pageInfo.getList())){
                for(EduStudentEnrollVO studentEnrollVO:pageInfo.getList()){
                    list.add(BeanUtil.beanToMap(studentEnrollVO,false,true));
                }
            }
            if(pageNum==1){
                if(excelWriter==null){
                    excelWriter=excelCommonHelper.createExcelWriter(excelModelVO,destFilePath,Integer.parseInt(total));
                }
                excelCommonHelper.writeMap(excelWriter,list);
            }else{
                excelCommonHelper.writeMap(excelWriter,list);
            }
            if(pageInfo.isHasNextPage()){
                pageNum=pageNum+1;
                setData(excelModelVO,excelWriter,destFilePath,vo,pageNum);
            }else {
                closeFlag = true;
            }
        }catch (AppException appEx){
            throw appEx;
        }catch (Exception e){
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        }finally {
            if(closeFlag&&excelWriter!=null){
                excelWriter.close();
            }
        }
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0030", title = "义务教育民办第一志愿摇号信息导入", funcType = FuncTypeEnum.other)
    public YwMbApplyFileVO inputYwMbApplyInfo(YwMbApplyFileVO vo, MultipartFile file) {
        int year = eduHelper.thisYear();
        String schoolId = "";
        if(StringUtils.isEmpty(vo.getSchoolId())) {
             schoolId = SessionUtil.getSessionInfo().getOrgId();
        }else {
            schoolId = vo.getSchoolId();
        }
        QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper=new QueryWrapper<>();
        brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,year)
                .eq(EduEnrollmenBrochure::getSchoolId,schoolId);
        EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(brochureQueryWrapper,false);
        if(eduEnrollmenBrochure==null){
            throw new AppException("未找到学校招生方案信息");
        }
        EduSchool eduSchool=eduSchoolService.getById(schoolId);
        if("1".equals(eduSchool.getSchoolNature())){
            //民办
            if("1".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("第一志愿招生已停止，不能导入");
                }
            }else if("2".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
                    throw new AppException("第二志愿招生已停止，不能导入");
                }
            }else if("3".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
                    throw new AppException("第三志愿招生已停止，不能导入");
                }
            }else if("4".equals(vo.getAspirationType())){
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())){
                    throw new AppException("第四志愿招生已停止，不能导入");
                }
            }else{
                if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                    throw new AppException("招生已停止，不能导入");
                }
            }
        }else{
            if(BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                throw new AppException("招生已停止，不能导入");
            }
        }
        List<EduStudentEnrollVO> studentEnrollVOList =new ArrayList<>();
        List<EduStudentEnrollVO> studentEnrollVOList2 =new ArrayList<>();
        ExcelVO excelVO = Convert.convert(ExcelVO.class,vo);
        ExcelModelVO excelModelVO = excelIntegration.getModel(excelVO);
        InputStream in = null;
        try {
            in = file.getInputStream();
            List<Map<String, Object>> list = excelCommonHelper.readExcel(excelModelVO, in, true);
            JSONArray jsonArray = new JSONArray();
            jsonArray.addAll(list);
            studentEnrollVOList2 = jsonArray.toJavaList(EduStudentEnrollVO.class);

            //捆绑摇号
            for (EduStudentEnrollVO eduStudentEnrollVO : studentEnrollVOList2) {
                if(eduStudentEnrollVO.getApplyId().contains(",")){
                    String[] applyIdArray = eduStudentEnrollVO.getApplyId().split(",");
                    String[] fullNameArray = eduStudentEnrollVO.getFullName().split(",");
                    String[] idCardArray = eduStudentEnrollVO.getIdcard().split(",");
                    for (int i = 0; i < applyIdArray.length; i++) {
                        EduStudentEnrollVO enroll = new EduStudentEnrollVO();
                        enroll.setApplyId(applyIdArray[i]);
                        enroll.setFullName(fullNameArray[i]);
                        enroll.setIdcard(idCardArray[i]);
                        enroll.setSerialNum(eduStudentEnrollVO.getSerialNum());
                        studentEnrollVOList.add(enroll);
                    }
                }else {
                    studentEnrollVOList.add(eduStudentEnrollVO);
                }
            }

        } catch (IOException e) {
            throw new AppException("导入异常："+e.getMessage());
        }
        if(CollectionUtils.isEmpty(studentEnrollVOList)){
            throw new AppException("导入数据不能为空");
        }

        for(EduStudentEnrollVO item: studentEnrollVOList) {
            if(item.getSerialNum() == null) {
                throw new AppException("存在摇号序号为空的条目！");
            }
        }

        String redisKey=REDIS_YHDR+schoolId;
        if(redisHelper.hasKey(redisKey)){
            throw new AppException("上一次导入正在处理中，不能导入");
        }else{
            redisHelper.set(redisKey,"1",300);
        }
        //过滤报名编号为空数据
        studentEnrollVOList=studentEnrollVOList.stream()
                .filter(
                        filterItem ->StringUtils.isNotBlank(filterItem.getApplyId()))
                .collect(Collectors.toList());

        List<EduStudentEnrollVO> errorList = new ArrayList<>();
        QueryWrapper<EduStudentEnroll> existsQueryWrapper = new QueryWrapper<>();
        existsQueryWrapper
                .lambda()
                .eq(EduStudentEnroll::getSchoolId,schoolId)
                .in(
                        EduStudentEnroll::getApplyId,
                        studentEnrollVOList.stream()
                                .map(EduStudentEnrollVO::getApplyId)
                                .collect(Collectors.toList()));
        List<EduStudentEnroll> studentEnrollList =
                eduStudentEnrollService.list(existsQueryWrapper);
        if(CollectionUtils.isEmpty(studentEnrollList)){
            redisHelper.del(redisKey);
            throw new AppException("导入的报名编号在系统中未匹配到数据");
        }

        List<String> applyIdList =
                studentEnrollList.stream()
                        .map(EduStudentEnroll::getApplyId)
                        .collect(Collectors.toList());
        List<String> idcardList = new ArrayList<>();
        List<EduStudentEnroll> successList = new ArrayList<>();
        studentEnrollVOList.forEach(
                item -> {
                    if (item.getApplyId() == null || item.getSerialNum() == null) {
                        redisHelper.del(redisKey);
                        throw new AppException("模板有误!");
                    }
                    String remarks = "";
                    boolean flag = false;
                    if (!ObjectUtils.isEmpty(item.getIdcard())) {
                        if (idcardList.contains(item.getIdcard())) {
                            remarks += "存在重复学生身份证！";
                            flag = true;
                        } else {
                            idcardList.add(item.getIdcard());
                        }
                    }
                    if (!applyIdList.contains(item.getApplyId())) {
                        remarks += "根据报名编号查询不到学生信息！";
                        flag = true;
                    } else {
                        EduStudentEnroll eduStudentEnroll =
                                studentEnrollList.stream()
                                        .filter(
                                                filterItem ->
                                                        Objects.equals(
                                                                filterItem.getApplyId(),
                                                                item.getApplyId()))
                                        .collect(Collectors.toList())
                                        .get(0);
                        if(eduStudentEnroll.getEnrollStatus().equals(EnrollStatusFormalEnum.lq.getType())){
                            redisHelper.del(redisKey);
                            throw new AppException("录取工作已开始后不能导入摇号结果");
                        }
                        if(!eduStudentEnroll.getEnrollStatus().equals(EnrollStatusFormalEnum.dlq.getType())){
                            redisHelper.del(redisKey);
                            throw new AppException("数据异常：人员数据不是待录取状态，请联系管理员查找原因");
                        }
                        if (!ObjectUtils.isEmpty(item.getFullName())
                                && !StringUtils.equals(
                                item.getFullName(), eduStudentEnroll.getFullName())) {
                            remarks += "学生姓名预系统中的不匹配！";
                            flag = true;
                        }
                        if (!ObjectUtils.isEmpty(item.getIdcard())
                                && !StringUtils.equals(
                                item.getIdcard(), eduStudentEnroll.getIdcard())) {
                            remarks += "学生证件号码与系统中的不匹配！";
                            flag = true;
                        }

                        item.setStudentEnrollId(eduStudentEnroll.getStudentEnrollId());
                        if (!flag) {
                            eduStudentEnroll.setSerialNum(item.getSerialNum());
                            successList.add(eduStudentEnroll);
                            eduEnrollClearCacheHelper.clearCacheMyEnroll(eduStudentEnroll.getIdcard());
                            eduEnrollClearCacheHelper.clearCacheMyEnroll(eduStudentEnroll.getFatherIdcard());
                            eduEnrollClearCacheHelper.clearCacheMyEnroll(eduStudentEnroll.getMotherIdcard());

                        }
                    }
                    if (flag) {
                        item.setRemarks(remarks);
                        errorList.add(item);
                    }
                });
        vo.setErrorList(errorList);
        vo.setErrorId(IdUtil.simpleUUID());

        if(!CollectionUtils.isEmpty(successList)){
            eduStudentEnrollService.updateBatchById(successList);
            vo.setSuccessList(Convert.toList(EduStudentEnrollVO.class,successList));

        }
        redisHelper.del(redisKey);
        return vo;
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0031", title = "义务教育民办第一志愿停止招生", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0031",
            operationName = "义务教育民办第一志愿停止招生",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMbStop(StudentEnrollStopVO vo) {
        vo.setAspirationType("1");
        this.ywStop(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0032", title = "义务教育民办第一志愿审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0032",
            operationName = "义务教育民办第一志愿审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMbAudit(StudentEnrollSaveVO vo) {
        this.auth(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0033", title = "义务教育民办第一志愿单个录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0033",
            operationName = "义务教育民办第一志愿单个录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public StudentEnrollLqVO ywMbApply(StudentEnrollSaveVO vo){
        return this.admit(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0034", title = "获取义务教育民办第一志愿报名列表信息", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollVO> getYwMbApplyInfo(EduStudentEnrollQueryVO vo) {
        vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        vo.setAspirationType("1");
        vo.setOpType("1");
        PageInfo<EduStudentEnrollVO> pageInfo= this.getYwApplyList(vo);
        return pageInfo;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0035", title = "义务教育民办第二志愿报名摇号信息导出", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void exportYwMbApplyInfo2(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        vo.setOpType("3");
        this.exportYwMbApplyInfo(vo,response);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0036", title = "义务教育民办第二志愿摇号信息导入", funcType = FuncTypeEnum.other)
    public YwMbApplyFileVO inputYwMbApplyInfo2(YwMbApplyFileVO vo, MultipartFile file) {
        return this.inputYwMbApplyInfo(vo,file);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0037", title = "义务教育民办第二志愿批量录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0037",
            operationName = "义务教育民办第二志愿批量录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void batchAdmit2(StudentEnrollBatchVO vo) {
        this.batchAdmit(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0038", title = "义务教育民办第二志愿停止招生", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0038",
            operationName = "义务教育民办第二志愿停止招生",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMbStop2(StudentEnrollStopVO vo) {
        vo.setAspirationType("2");
        this.ywStop(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0039", title = "义务教育民办第二志愿审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0039",
            operationName = "义务教育民办第二志愿审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMbAudit2(StudentEnrollSaveVO vo) {
        this.auth(vo);
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0040", title = "义务教育民办第二志愿单个录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0040",
            operationName = "义务教育民办第二志愿单个录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public StudentEnrollLqVO ywMbApply2(StudentEnrollSaveVO vo){
        return this.admit(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0041", title = "获取义务教育民办第二志愿报名列表信息", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollVO> getYwMbApplyInfo2(EduStudentEnrollQueryVO vo) {
        vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        vo.setAspirationType("2");
        vo.setOpType("3");
        PageInfo<EduStudentEnrollVO> pageInfo= this.getYwApplyList(vo);
        return pageInfo;
    }
    @Override
    @OpApi(funcCode = "eduStudentEnroll0052", title = "义务教育民办第三志愿报名摇号信息导出", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void exportYwMbApplyInfo3(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        vo.setOpType("4");
        this.exportYwMbApplyInfo(vo,response);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0053", title = "义务教育民办第三志愿摇号信息导入", funcType = FuncTypeEnum.other)
    public YwMbApplyFileVO inputYwMbApplyInfo3(YwMbApplyFileVO vo, MultipartFile file) {
        return this.inputYwMbApplyInfo(vo,file);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0054", title = "义务教育民办第三志愿批量录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0054",
            operationName = "义务教育民办第三志愿批量录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void batchAdmit3(StudentEnrollBatchVO vo) {
        this.batchAdmit(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0055", title = "义务教育民办第三志愿停止招生", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0055",
            operationName = "义务教育民办第三志愿停止招生",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMbStop3(StudentEnrollStopVO vo) {
        vo.setAspirationType("3");
        this.ywStop(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0056", title = "义务教育民办第三志愿审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0056",
            operationName = "义务教育民办第三志愿审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywMbAudit3(StudentEnrollSaveVO vo) {
        this.auth(vo);
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0057", title = "义务教育民办第三志愿单个录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0057",
            operationName = "义务教育民办第三志愿单个录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public StudentEnrollLqVO ywMbApply3(StudentEnrollSaveVO vo){
        return this.admit(vo);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0058", title = "获取义务教育民办第三志愿报名列表信息", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollVO> getYwMbApplyInfo3(EduStudentEnrollQueryVO vo) {
        vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        vo.setAspirationType("3");
        vo.setOpType("4");
        PageInfo<EduStudentEnrollVO> pageInfo= this.getYwApplyList(vo);
        return pageInfo;
    }





    @Override
    @OpApi(funcCode = "eduStudentEnroll0042", title = "获取义务教育公办报名列表查询信息", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollVO> getYwGbApplyInfo(EduStudentEnrollQueryVO vo) {
        vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        vo.setOpType("0");
        PageInfo<EduStudentEnrollVO> pageInfo= this.getYwApplyList(vo);
        return pageInfo;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0043", title = "义务教育公办报名审核", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0043",
            operationName = "义务教育公办报名审核",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywGbAudit(StudentEnrollSaveVO vo) {
        this.auth(vo);
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0044", title = "义务教育公办报名录取", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0044",
            operationName = "义务教育公办报名录取",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public StudentEnrollLqVO ywGbApply(StudentEnrollSaveVO vo){
        return this.admit(vo);
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0045", title = "义务教育公办报名信息导出", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void exportYwGbApplyInfo(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        vo.setSchoolId(SessionUtil.getOrgId());
        vo.setOpType("0");
        if(vo.getYear()==null){
            throw new AppException("招生年度不能为空");
        }
        this.exportYwApplyInfo(vo,response);
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0046", title = "义务教育公办结束招生", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0046",
            operationName = "义务教育公办结束招生",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void ywGbStop(StudentEnrollStopVO vo) {
        if(StringUtils.isBlank(vo.getSchoolId())){
            vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        }
        String reidsKey=stopKey+vo.getSchoolId();
        if(redisHelper.hasKey(reidsKey)){
            throw new AppException("系统正在执行中，请稍后！");
        }

        int year = eduHelper.thisYear();
        EnrollCheckShLqVO checkShLqVO=new EnrollCheckShLqVO();
        checkShLqVO.setSchoolId(vo.getSchoolId());
        checkShLqVO.setYear(year);
        checkShLqVO.setOpType("0");
        this.checklq(checkShLqVO);
        QueryWrapper<EduEnrollmenBrochure> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().eq(EduEnrollmenBrochure::getYear,year)
                .eq(EduEnrollmenBrochure::getSchoolId,vo.getSchoolId());
        EduEnrollmenBrochure eduEnrollmenBrochure=eduEnrollmenBrochureService.getOne(queryWrapper,false);
        if(eduEnrollmenBrochure==null){
            throw new AppException("未找到招生方案信息");
        }
        if(StringUtils.isBlank(vo.getAspirationType())){
            vo.setAspirationType("1");
        }
        if("1".equalsIgnoreCase(vo.getAspirationType())&&BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
            throw new AppException("已停止招生");
        }
        if("2".equalsIgnoreCase(vo.getAspirationType())&&BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
            throw new AppException("第二志愿已停止招生");
        }
        if("3".equalsIgnoreCase(vo.getAspirationType())&&BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
            throw new AppException("第三志愿已停止招生");
        }
        if("4".equalsIgnoreCase(vo.getAspirationType())&&BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())){
            throw new AppException("第四志愿已停止招生");
        }
        if("1".equalsIgnoreCase(vo.getAspirationType())) {
            eduEnrollmenBrochure.setEndRegistration(BoolEnum.TRUE.getType());
        }
        if("2".equalsIgnoreCase(vo.getAspirationType())) {
            if(!BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())){
                throw new AppException("请先停止第一志愿招生");
            }
            eduEnrollmenBrochure.setEndRegistration2(BoolEnum.TRUE.getType());
        }
        if("3".equalsIgnoreCase(vo.getAspirationType())) {
            if(!BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())){
                throw new AppException("请先停止第二志愿招生");
            }
            eduEnrollmenBrochure.setEndRegistration3(BoolEnum.TRUE.getType());
        }
        if("4".equalsIgnoreCase(vo.getAspirationType())) {
            if(!BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())){
                throw new AppException("请先停止第三志愿招生");
            }
            eduEnrollmenBrochure.setEndRegistration4(BoolEnum.TRUE.getType());
        }
        eduEnrollmenBrochureService.updateById(eduEnrollmenBrochure);
        //所有未录取的改成不录取
        List<String> dlqList=new ArrayList<>();
        dlqList.add(EnrollStatusFormalEnum.dlq.getType());
        dlqList.add(EnrollStatusFormalEnum.dsh.getType());
        QueryWrapper<EduStudentEnroll> studentEnrollQueryWrapper = new QueryWrapper<>();
        studentEnrollQueryWrapper.lambda().eq(EduStudentEnroll::getSchoolId, vo.getSchoolId())
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getAspirationType,vo.getAspirationType())
                .in(EduStudentEnroll::getEnrollStatus,dlqList);
        List<EduStudentEnroll> studentEnrollList =
                eduStudentEnrollService.list(studentEnrollQueryWrapper);
        if (!CollectionUtils.isEmpty(studentEnrollList)) {
            studentEnrollList.forEach(
                    item -> {
                        if (item.getAuthStatus().equals(AuthStatusEnum.NODO.getType())) {
                            item.setAuthStatus(AuthStatusEnum.NO.getType());
                            item.setAuthTime(new Date());
                            item.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
                            item.setAuthRemarks("停止招生，批量改为审核不通过");
                        }
                        item.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
                        item.setAdmitFlag(BoolEnum.FALSE.getType());
                        item.setAdmitTime(new Date());
                        item.setAdmitRemarks("停止招生，批量改为不录取");
                    });
            try {
                redisHelper.set(reidsKey, 1, 600);
                eduStudentEnrollService.updateBatchById(studentEnrollList);
            } catch (Exception e) {
                throw new AppException("保存数据异常" + e.getMessage());
            } finally {
                redisHelper.del(reidsKey);
            }
            studentEnrollList.forEach(item -> {
                eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnroll(item.getMotherIdcard());
            });
        }
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0047", title = "根据学校id配置表查询", funcType = FuncTypeEnum.query, checkPrivilege = BoolEnum.FALSE)
    public List<SchoolConfigVO> querySchoolConfigBySchoolId(SchoolConfigQueryVO vo) {
        if(StringUtils.isBlank(vo.getOrgId())){
            throw new AppException("学校id不能为空");
        }
        int year;
        String orgId = vo.getOrgId();
        QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper = new QueryWrapper<>();
        brochureQueryWrapper
                .lambda()
                .eq(EduEnrollmenBrochure::getSchoolId, orgId)
                .orderByDesc(EduEnrollmenBrochure::getYear)
                .last("limit 1");
        if(vo.getYear()!=null){
            brochureQueryWrapper
                    .lambda()
                    .eq(EduEnrollmenBrochure::getYear, vo.getYear());
        }
        EduEnrollmenBrochure brochure =
                eduEnrollmenBrochureService.getOne(brochureQueryWrapper, false);
        if (ObjectUtils.isEmpty(brochure)) {
            throw new AppException("查询不到招生方案信息");
        } else {
            year = brochure.getYear();
        }
        String eFlag="0";
        QueryWrapper<EduAppointSchool> eduAppointSchoolQueryWrapper=new QueryWrapper<>();
        eduAppointSchoolQueryWrapper.lambda().eq(EduAppointSchool::getNewSchoolId,orgId)
                .eq(EduAppointSchool::getStatus,BoolEnum.TRUE.getType())
                .eq(EduAppointSchool::getYear,year);
        if(eduAppointSchoolService.count(eduAppointSchoolQueryWrapper)>0){
            eFlag="1";
        }
        SchoolConfigQueryVO schoolConfigQueryVO=new SchoolConfigQueryVO();
        schoolConfigQueryVO.setOrgId(vo.getOrgId());
        schoolConfigQueryVO.setAccessToken(vo.getAccessToken());
        schoolConfigQueryVO.setOpRouterId(vo.getOpRouterId());
        schoolConfigQueryVO.setYear(year);
        schoolConfigQueryVO.setStatus(BoolEnum.TRUE.getType());
        schoolConfigQueryVO.setAuthStatus(AuthStatusEnum.YES.getType());
        schoolConfigQueryVO.setZsFlag(vo.getZsFlag());
        if(StringUtils.isBlank(vo.getSpecialFlag())){
            schoolConfigQueryVO.setSpecialFlag(BoolEnum.FALSE.getType());
        }else{
            schoolConfigQueryVO.setSpecialFlag(vo.getSpecialFlag());
        }
        PageInfo<SchoolConfigVO> pageInfo=eduSchoolConfigIntegration.getYwSchoolConfigInfo(schoolConfigQueryVO);
        List<SchoolConfigVO> list=pageInfo.getList();
        if(CollectionUtils.isEmpty(list)){
            return list;
        }

        for(SchoolConfigVO schoolConfigVO:list){
            schoolConfigVO.setEFlag(eFlag);
        }
        //List<String> configTypeNameList=list.stream().map(SchoolConfigVO::getConfigTypeName).distinct().collect(Collectors.toList());
        //公办认为只有一个招生计划的类别，所以查询时候不做控制，民办目前不配表单

        if(BoolEnum.FALSE.getType().equals(schoolConfigQueryVO.getSpecialFlag())){
            QueryWrapper<EduFormEnroll> formQueryWrapper = new QueryWrapper<>();
            formQueryWrapper
                    .lambda()
                    .eq(EduFormEnroll::getSchoolId, orgId)
                    //.in(EduFormEnroll::getConfigTypeName, configTypeNameList)
                    .eq(EduFormEnroll::getStatus, "on")
                    .eq(EduFormEnroll::getYear, year)
                    .orderByAsc(EduFormEnroll::getOrderNo);
            List<EduFormEnroll> form = eduFormEnrollService.list(formQueryWrapper);
            if (CollectionUtils.isEmpty(form)) {
                return list;
            }
            List<FormAppQueryVO> formAppQueryVO = Convert.toList(FormAppQueryVO.class, form);
            dictHelper.valueToName(formAppQueryVO, Arrays.asList(EduFormEnrollDictEnum.values()));
            for(SchoolConfigVO schoolConfigVO:list){
                if(StringUtils.isNotBlank(schoolConfigVO.getConfigTypeName())){
                    schoolConfigVO.setFormList(formAppQueryVO);
                }
            }
        }else{
            if(StringUtils.isBlank(brochure.getSpecialIds())){
                return list;
            }
            List<String> specialIdList=Arrays.stream(brochure.getSpecialIds().split(",")).map(s -> s).collect(Collectors.toList());
            QueryWrapper<EduFormSpecial> formQueryWrapper = new QueryWrapper<>();
            formQueryWrapper
                    .lambda()
                    .in(EduFormSpecial::getFormSpecialId, specialIdList)
                    //.in(EduForm::getConfigTypeName, configTypeNameList)
                    .eq(EduFormSpecial::getStatus, BoolEnum.TRUE.getType())
                    .eq(EduFormSpecial::getYear, year)
                    .orderByAsc(EduFormSpecial::getOrderNo);
            List<EduFormSpecial> form = eduFormSpecialService.list(formQueryWrapper);
            if (CollectionUtils.isEmpty(form)) {
                return list;
            }
            List<FormAppQueryVO> formAppQueryVO = new ArrayList<>();
            for(EduFormSpecial eduFormSpecial:form){
                FormAppQueryVO formVO=new FormAppQueryVO();
                formVO.setFormId(eduFormSpecial.getFormSpecialId());
                formVO.setConfigType(eduFormSpecial.getSmallClassKey()+"");
                formVO.setFormType(eduFormSpecial.getBigClassKey()+"");
                formVO.setFormClass(eduFormSpecial.getSmallClassKey()+"");
                formVO.setConfigName(eduFormSpecial.getSmallClassValue());
                formVO.setConfigTypeName(eduFormSpecial.getBigClassValue());
                formAppQueryVO.add(formVO);
            }
            for(SchoolConfigVO schoolConfigVO:list){
                if(StringUtils.isNotBlank(schoolConfigVO.getConfigTypeName())){
                    schoolConfigVO.setFormList(formAppQueryVO);
                }
            }
        }

        return list;
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0048", title = "义务教育学校录入报名人员", funcType = FuncTypeEnum.update)
    @SaveOplog(
            operationType = "eduStudentEnroll0048",
            operationName = "义务教育学校录入报名人员",
            dataType = "studentEnrollId",
            auType = AuTypeEnum.OTHER)
    @Transactional
    public void schoolAddEnroll(SaveStudentEnrollVO vo) {

        EduStudentEnroll enroll = null;
        //义务端学校录入报名人员保存校验
        saveCheckStudentEnroll(vo);

        String schoolId = vo.getSchoolId();
        if (StringUtils.isBlank(schoolId)) {
            schoolId = SessionUtil.getSessionInfo().getOrgId();
        }
        EduSchool eduSchool = eduSchoolService.getById(schoolId);
        if (eduSchool == null) {
            throw new AppException("未找到学校信息");
        }
        vo.setSchoolName(eduSchool.getSchoolName());
        vo.setSchoolNature(eduSchool.getSchoolNature());
        vo.setStreet(eduSchool.getStreet());
        vo.setSchoolCategory(eduSchool.getSchoolCategory());
        vo.setAreaCode(eduSchool.getAreaCode());
        if (vo.getYear() == null) {
            int year;
            year = eduHelper.thisYear();
            vo.setYear(year);
        }

        //时间控制
        //判断是否在年度招生时间中
        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(vo.getAreaCode());
        queryVO.setYear(vo.getYear());
        EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
        if(eduOperationCacheVO==null){
            throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
        }
        Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();
        EduOperationCacheDetailVO xxOperation=operation.get("YW023");//学校录入时间
        if(xxOperation==null){
            throw new AppException(vo.getYear()+"年度义务段学校线下报名录入工作尚未开始");
        }
        if(!xxOperation.isFlag()){
            if ("1".equalsIgnoreCase(xxOperation.getType()) || "3".equalsIgnoreCase(xxOperation.getType())) {
                throw new AppException(vo.getYear()+"年度义务段学校线下报名录入工作尚未开始");
            }else{
                throw new AppException(vo.getYear()+"年度义务段学校线下报名录入工作已结束");
            }
        }
        //检验是否在黑名单中，黑名单中不能线下录入
        QueryWrapper<EduStudentEnrollBlacklist> blacklistQueryWrapper = new QueryWrapper<>();
        blacklistQueryWrapper.lambda().eq(EduStudentEnrollBlacklist::getIdcard, vo.getIdcard())
                .eq(EduStudentEnrollBlacklist::getYear, vo.getYear())
                .eq(EduStudentEnrollBlacklist::getStatus, BoolEnum.TRUE.getType())
                .eq(EduStudentEnrollBlacklist::getAreaCode, eduSchool.getAreaCode());
        if (eduStudentEnrollBlacklistService.count(blacklistQueryWrapper) > 0) {
            throw new AppException("该学生申请过退出东阳报名，不能重新录入");
        }
        //判断是否公办中系统无效，存在无效数据不能录入
        QueryWrapper<EduStudentEnroll> queryWrapperWx = new QueryWrapper<>();
        queryWrapperWx.lambda().eq(EduStudentEnroll::getIdcard,vo.getIdcard())
                .eq(EduStudentEnroll::getYear,vo.getYear())
                .eq(EduStudentEnroll::getEnrollStatus,EnrollStatusFormalEnum.xtblq.getType())
                .eq(EduStudentEnroll::getSchoolNature,SchoolNatureEnum.gb.getType());
        if (eduStudentEnrollService.count(queryWrapperWx)>0){
            throw new AppException("该学生存在公办学校报名无效数据，请联系基教科处理后才能录入");
        }
        //加锁进行判断
        RLock lock = redissonClient.getLock(EduCache.EDU_YW_STUDENT_ENROLL_LOCK + vo.getIdcard());
        boolean isGetLock = false ;
        try {
            isGetLock = lock.tryLock(5, 60, TimeUnit.SECONDS);
        } catch (InterruptedException e) {
            log.error("异常："+e.getMessage());
            throw new RuntimeException(e.getMessage());
        }
        if (isGetLock){
            try{
                //判断学校录入指标管理是否有配置存在
                QueryWrapper<EduSchoolLr> lrQueryWrapper = new QueryWrapper<>();
                lrQueryWrapper.lambda()
                        .eq(EduSchoolLr::getYear,vo.getYear())
                        .eq(EduSchoolLr::getSchoolId,vo.getSchoolId());
                EduSchoolLr schoolLr = eduSchoolLrService.getOne(lrQueryWrapper, false);
                if (ObjectUtils.isEmpty(schoolLr)){
                    throw new AppException("未配置学校线下录入指标，请联系教育局进行配置");
                }
                if (schoolLr.getLrCount() == 0){
                    throw new AppException(schoolLr.getSchoolName()+"的可录入人数为0，请联系教育局进行配置！");
                }
                long enrollStudentCount = eduStudentEnrollService.count(Wrappers.<EduStudentEnroll>lambdaQuery()
                        .eq(EduStudentEnroll::getYear, vo.getYear())
                        .eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.lq.getType())
                        .eq(EduStudentEnroll::getSchoolId, vo.getSchoolId())
                        .eq(EduStudentEnroll::getSource, "6"));
                if (enrollStudentCount >= schoolLr.getLrCount()){
                    throw new AppException("学校线下录入的人数大于系统配置人数指标，无法进行学生录入，请联系教育局进行配置");
                }

                List<String> enrollStatusList=new ArrayList<>();
                enrollStatusList.add(EnrollStatusFormalEnum.hy.getType());
                enrollStatusList.add(EnrollStatusFormalEnum.fs.getType());
                enrollStatusList.add(EnrollStatusFormalEnum.dsh.getType());
                enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
                enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
                QueryWrapper<EduStudentEnroll> otherQueryWrapper = new QueryWrapper<>();
                otherQueryWrapper.lambda().ne(EduStudentEnroll::getSchoolId, schoolId)
                        .eq(EduStudentEnroll::getYear, vo.getYear())
                        .in(EduStudentEnroll::getEnrollStatus, enrollStatusList)
                        .eq(EduStudentEnroll::getIdcard, vo.getIdcard());
                if (eduStudentEnrollService.count(otherQueryWrapper) > 0) {
                    throw new AppException("该学生已在市内其他学校待审核/待录取/录取，不能直接录入，如有疑问，请联系基教科核对");
                }
                if (StringUtils.isNotBlank(vo.getStudentEnrollId())) {
                    enroll = eduStudentEnrollService.getById(vo.getStudentEnrollId());
                    if ("2".equals(enroll.getEnrollStatus())) {
                        throw new AppException("该学生已是录取状态，请核对");
                    }
                    if(!enroll.getFormId().equalsIgnoreCase(vo.getFormId())){
                        enroll.setApplyId(null);
                    }

                } else {
                    QueryWrapper<EduStudentEnroll> enrollQueryWrapper = new QueryWrapper<>();
                    enrollQueryWrapper.lambda().eq(EduStudentEnroll::getSchoolId, schoolId)
                            .eq(EduStudentEnroll::getYear, vo.getYear())
                            .eq(EduStudentEnroll::getIdcard, vo.getIdcard());
                    List<EduStudentEnroll> eduStudentEnrollList = eduStudentEnrollService.list(enrollQueryWrapper);
                    if (!CollectionUtils.isEmpty(eduStudentEnrollList)) {
                        enroll = eduStudentEnrollList.get(0);
                        if ("2".equals(enroll.getEnrollStatus())) {
                            throw new AppException("该学生已是录取状态，请核对");
                        }
                        if ("3".equals(enroll.getEnrollStatus())) {
                            throw new AppException("该学生业务操作为不予录取，如需重新录入，请联系基教科处理数据");
                        }
                    } else {

                        enroll = Convert.convert(EduStudentEnroll.class, vo);
                        if ("0".equals(vo.getSchoolNature())) {
                            if(StringUtils.isBlank(vo.getConfigTypeName())){
                                vo.setConfigTypeName("公办");
                            }
                        }
                        enroll.setStudentEnrollId(IdUtil.simpleUUID());
                        enroll.setSchoolId(schoolId);
                    }
                }
                //进行学生录入
                QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper = new QueryWrapper<>();
                brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear, vo.getYear())
                        .eq(EduEnrollmenBrochure::getSchoolId, vo.getSchoolId());
                EduEnrollmenBrochure eduEnrollmenBrochure = eduEnrollmenBrochureService.getOne(brochureQueryWrapper, false);
                if (eduEnrollmenBrochure == null) {
                    throw new AppException("未找到招生方案信息");
                }
                //超过计划数不能录取
                QueryWrapper<EduSchoolConfig> configQueryWrapper = new QueryWrapper<>();
                configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment, EduSchoolConfig::getSerialNumEnd)
                        .eq(EduSchoolConfig::getSchoolId, vo.getSchoolId())
                        .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
                        .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                        .eq(EduSchoolConfig::getYear, vo.getYear());
                if ("1".equals(vo.getSchoolNature()) || "2".equals(vo.getSchoolNature())) {

                    //民办
                    configQueryWrapper.lambda().eq(EduSchoolConfig::getConfigTypeName, vo.getConfigTypeName());
                }
                EduSchoolConfig eduSchoolConfig = eduSchoolConfigService.getOne(configQueryWrapper, false);
                StudentEnrollLqVO retVO = new StudentEnrollLqVO();
                //计划人数
                Integer enrolment = 0;
                if (eduSchoolConfig != null) {
                    enrolment = eduSchoolConfig.getEnrolment() == null ? 0 : eduSchoolConfig.getEnrolment();
                }
                //已录取人数
                QueryWrapper<EduStudentEnroll> lqQuery = new QueryWrapper<>();
                lqQuery.lambda().eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.lq.getType())
                        .eq(EduStudentEnroll::getYear, vo.getYear())
                        .eq(EduStudentEnroll::getAdmitFlag, BoolEnum.TRUE.getType())
                        .eq(EduStudentEnroll::getSchoolId, vo.getSchoolId());
                if ("1".equals(vo.getSchoolNature()) || "2".equals(vo.getSchoolNature())) {
                    //民办
                    lqQuery.lambda().eq(EduStudentEnroll::getConfigTypeName, vo.getConfigTypeName());
                }
                Long lqCount = eduStudentEnrollService.count(lqQuery);
                if (lqCount >= enrolment) {
                    throw new AppException("录取人数已到达计划人数，如还需录取，请联系基教科修改招生计划");
                }
                enroll.setConfigName(vo.getConfigName());
                enroll.setConfigTypeName(vo.getConfigTypeName());
                enroll.setFormId(vo.getFormId());
                enroll.setRemarks(vo.getRemarks());
                enroll.setSource("6");//学校录入
                enroll.setAdmitFlag(BoolEnum.TRUE.getType());
                enroll.setAuthStatus(AuthStatusEnum.YES.getType());
                enroll.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
                enroll.setAuthTime(new Date());
                enroll.setEnrollStatus("2");
                enroll.setParam20(vo.getParam20());
                enroll.setAdmitTime(new Date());
                enroll.setAspirationType("1");
                enroll.setAdmitRemarks("学校直接录入录取");
                enroll.setDeployFlag(BoolEnum.FALSE.getType());
                QueryWrapper<EduStudentEnroll> enrollQueryWrapper = new QueryWrapper<>();
                enrollQueryWrapper.lambda().eq(EduStudentEnroll::getYear, enroll.getYear())
                        .eq(EduStudentEnroll::getIdcard, enroll.getIdcard())
                        .eq(EduStudentEnroll::getEnrollStatus, "2")
                        .ne(EduStudentEnroll::getSchoolId, schoolId);
                if (eduStudentEnrollService.count(enrollQueryWrapper) > 0) {
                    throw new AppException("已被东阳市其他学校录取");
                }
                // 调用金华接口判断是否已录取
                CommonVO commonVO = new CommonVO();
                commonVO.setParamKey("localLqDw");
                commonVO.setAreaCode(vo.getAreaCode());
                String localDw = commonIntegration.getValueByKeyAndArea(commonVO);
                if(StringUtils.isBlank(localDw)){
                    throw new AppException("请先配置金华教育本地录取单位");
                }
                EduJhjyQuerySyncVO eduJhjyQuerySyncVO = eduJhjyQuerySyncIntegration.queryJhjy(enroll);
                if (StringUtils.isNotBlank(eduJhjyQuerySyncVO.getLqDw())&&!localDw.equals(eduJhjyQuerySyncVO.getLqDw())) {
                    throw new AppException("该学生已被" + eduJhjyQuerySyncVO.getLqDw() + "录取，请联系基教科处理");
                }
                //修改其他学校为无效
                List<String> enrollStatus1List = new ArrayList<>();
                enrollStatus1List.add(EnrollStatusFormalEnum.dsh.getType());
                enrollStatus1List.add(EnrollStatusFormalEnum.dlq.getType());
                QueryWrapper<EduStudentEnroll> otherQuery = new QueryWrapper<>();
                otherQuery.lambda().ne(EduStudentEnroll::getSchoolId, enroll.getSchoolId())
                        .eq(EduStudentEnroll::getIdcard, enroll.getIdcard())
                        .eq(EduStudentEnroll::getYear, enroll.getYear())
                        .in(EduStudentEnroll::getEnrollStatus, enrollStatus1List);
                List<EduStudentEnroll> otherList = eduStudentEnrollService.list(otherQuery);
                if (!CollectionUtils.isEmpty(otherList)) {
                    for (EduStudentEnroll otherEnroll : otherList) {
                        otherEnroll.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
                        otherEnroll.setAdmitFlag(BoolEnum.FALSE.getType());
                        otherEnroll.setAdmitRemarks("因其他优先级高的学校录取，系统自动设置为不录取");
                        if (otherEnroll.getAuthStatus().equals(AuthStatusEnum.NODO.getType())) {
                            otherEnroll.setAuthStatus(AuthStatusEnum.NO.getType());
                            otherEnroll.setAuthRemarks("因其他优先级高的学校录取，系统自动设置为审核不通过");
                            otherEnroll.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
                        }
                        otherEnroll.setAdmitUserId(SessionUtil.getSessionInfo().getUserId());
                        eduStudentEnrollService.updateById(otherEnroll);
                    }
                }
                this.setPersonId(enroll);
                if (StringUtils.isBlank(enroll.getApplyId())) {
                    Integer orderNo = 0;
                    if ("0".equals(enroll.getSchoolNature())) {
                        if (StringUtils.isBlank(enroll.getFormId())) {
                            throw new AppException("报名表单id不能为空");
                        }
                        EduFormEnroll eduFormEnroll = eduFormEnrollService.getById(enroll.getFormId());
                        enroll.setSpecialFlag(BoolEnum.FALSE.getType());
                        if (eduFormEnroll == null) {
                            EduFormSpecial eduFormSpecial = eduFormSpecialService.getById(enroll.getFormId());
                            if (eduFormSpecial == null) {
                                throw new AppException("未匹配到学校配置的报名表单，如果疑问，请拨打学校电话了解详细情况");
                            }
                            orderNo = 99;
                            enroll.setConfigTypeName(eduFormSpecial.getBigClassValue());
                            enroll.setSpecialFlag(BoolEnum.TRUE.getType());

                        }else{
                            if (!eduFormEnroll.getValidStatus().equals(BoolEnum.TRUE.getType())) {
                                throw new AppException("学校配置报名表单已无效，如果疑问，请拨打学校电话了解详细情况");
                            }
                            orderNo = eduFormEnroll.getOrderNo();
                            //判断年龄是否符合，不是特殊通道类别，需要判断年龄
                            if (StringUtils.isBlank(vo.getBirthYmd())) {
                                throw new AppException("出生日期不能为空");
                            }
                            String birthday = "";
                            if (vo.getBirthYmd().length() >= 8) {
                                birthday = vo.getBirthYmd().replaceAll("-", "").replaceAll("/", "");
                            } else if (vo.getBirthYmd().length() == 6) {
                                birthday = vo.getBirthYmd() + "01";
                            } else {
                                throw new AppException("出生日期格式不正确");
                            }
                            Integer birthYmd = Integer.parseInt(birthday);
                            if (eduSchoolConfig.getStartAge() != null) {
                                Integer startBirthday =
                                        Integer.parseInt(
                                                DatePattern.PURE_DATE_FORMAT.format(eduSchoolConfig.getStartAge()));
                                if (birthYmd < startBirthday) {
                                    throw new AppException("年龄不符，如有疑问，请拨打学校电话了解详细情况");
                                }
                            }
                            if (eduSchoolConfig.getEndAge() != null) {
                                Integer endBirthday =
                                        Integer.parseInt(
                                                DatePattern.PURE_DATE_FORMAT.format(eduSchoolConfig.getEndAge()));
                                if (birthYmd > endBirthday) {
                                    throw new AppException("年龄不符，如有疑问，请拨打学校电话了解详细情况");
                                }
                            }
                        }

                    } else {

                        if (StringUtils.isBlank(enroll.getConfigTypeName())) {
                            throw new AppException(eduSchool.getSchoolName() + "的报名类别不能为空");
                        }
                        QueryWrapper<EduSchoolConfig> schoolConfigMbQueryWrapper = new QueryWrapper<>();
                        schoolConfigMbQueryWrapper
                                .lambda()
                                .eq(EduSchoolConfig::getSchoolId, enroll.getSchoolId())
                                .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
                                .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                                .eq(EduSchoolConfig::getConfigTypeName, enroll.getConfigTypeName())
                                .eq(EduSchoolConfig::getYear, enroll.getYear());
                        EduSchoolConfig schoolConfigMb = eduSchoolConfigService.getOne(schoolConfigMbQueryWrapper, false);
                        if (schoolConfigMb == null) {
                            throw new AppException(enroll.getYear() + "年度报名学校报名类别不匹配，如有疑问，请拨打学校电话了解详细情况");
                        }
                        if (schoolConfigMb.getOrderNo() == null) {
                            throw new AppException(enroll.getYear() + "年度报名学校招生计划设置有误，如有疑问，请拨打学校电话了解详细情况");
                        }
                        orderNo = schoolConfigMb.getOrderNo();
                    }
                    String applyId = this.getApplyId(enroll.getYear(), enroll.getSchoolNature(), eduSchool.getSchoolNum(), orderNo, enroll.getSchoolId(), 1);
                    enroll.setApplyId(applyId);
                }
                //判断是否随迁
                if (StringUtils.isBlank(enroll.getFollowingFlag())) {
                    QueryWrapper<EduHousehold> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(EduHousehold::getYear, enroll.getYear())
                            .eq(EduHousehold::getIdcard, enroll.getIdcard())
                            .eq(EduHousehold::getAuthStatus, AuthStatusEnum.YES.getType())
                            .eq(EduHousehold::getAreaCode, enroll.getAreaCode());
                    if (eduHouseholdService.count(queryWrapper) > 0) {
                        //有户籍认为非随迁
                        enroll.setFollowingFlag(BoolEnum.TRUE.getType());
                    } else {
                        if (BoolEnum.TRUE.getType().equalsIgnoreCase(enroll.getSpecialFlag())) {
                            //特殊通道认为非随迁
                            enroll.setFollowingFlag(BoolEnum.TRUE.getType());
                        } else {
                            if ("A".equalsIgnoreCase(enroll.getConfigName()) || "B".equalsIgnoreCase(enroll.getConfigName())) {
                                //A类B类认为是非随迁
                                enroll.setFollowingFlag(BoolEnum.TRUE.getType());
                            } else {
                                enroll.setFollowingFlag(BoolEnum.FALSE.getType());
                            }
                        }
                    }
                }
                try {
                    eduStudentEnrollService.saveOrUpdate(enroll);
                } catch (Exception e) {
                    throw new AppException("报名编号重复，请重新点击保存");
                }
                insertEduStudentEnrollPre(vo);
            }catch (Exception e){
                throw new AppException(e.getMessage());
            }finally {
                lock.unlock();
            }
        }

    }

    /**
     * 判断预采集中是否有数据，如果没有就进行增加
     * @param vo
     */
    private void insertEduStudentEnrollPre(SaveStudentEnrollVO vo) {
        QueryWrapper<EduStudentEnrollPre> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EduStudentEnrollPre::getYear,eduHelper.thisYear())
                .eq(EduStudentEnrollPre::getIdcard,vo.getIdcard());
        if (eduStudentEnrollPreService.count(queryWrapper) == 0){
            //没有预采集数据，需要新增预采集数据
            EduStudentEnrollPre eduStudentEnrollPre = new EduStudentEnrollPre();
            BeanUtil.copyProperties(vo,eduStudentEnrollPre);
            eduStudentEnrollPre.setEnrollPreType(EnrollPreTypeEnum.lr.getType());
            eduStudentEnrollPre.setAuthStatus(AuthStatusEnum.YES.getType());
            eduStudentEnrollPreService.save(eduStudentEnrollPre);
        }

    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0050", title = "管理员查询摇号数据", funcType = FuncTypeEnum.query)
    public PageInfo<EduStudentEnrollVO> getEnrollLottery(EduStudentEnrollQueryVO vo) {

        // 开启分页
        if (vo.getPageNum() == null || vo.getPageSize() == null) {
            //如果不传入分页参数，默认最大取1000条
            vo.setPageNum(1);
            vo.setPageSize(1000);
        }
        PageHelper.startPage(vo.getPageNum(),vo.getPageSize());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper = new QueryWrapper<>();
        //摇号数据只取审核通过待录取数据
        enrollQueryWrapper.lambda()
                .eq(EduStudentEnroll::getYear,vo.getYear())
                .eq(EduStudentEnroll::getSchoolId,vo.getSchoolId())
                .eq(vo.getConfigNameNum()!=null,EduStudentEnroll::getConfigNameNum,vo.getConfigNameNum())
                .in(!CollectionUtils.isEmpty(vo.getConfigNameNumList()),EduStudentEnroll::getConfigNameNum,vo.getConfigNameNumList())
                .eq(StringUtils.isNotBlank(vo.getFatherIdcard()),EduStudentEnroll::getFatherIdcard,vo.getFatherIdcard())
                .eq(StringUtils.isNotBlank(vo.getConfigTypeName()),EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .eq(StringUtils.isNotBlank(vo.getAspirationType()),EduStudentEnroll::getAspirationType,vo.getAspirationType())
                .eq(StringUtils.isNotBlank(vo.getFollowingFlag()),EduStudentEnroll::getFollowingFlag,vo.getFollowingFlag())
                .eq(EduStudentEnroll::getEnrollStatus,vo.getEnrollStatus())
                .orderByAsc(EduStudentEnroll::getSerialNum);
        List<EduStudentEnroll> list = eduStudentEnrollService.list(enrollQueryWrapper);

        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduStudentEnroll> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduStudentEnrollVO> resultList = Convert.toList(EduStudentEnrollVO.class, pageInfo.getList());

        // 转义数据字典值
        dictHelper.valueToName(resultList, Arrays.asList(EduYwEnrollDictEnum.values()));
        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }


    @Override
    @OpApi(funcCode = "eduStudentEnroll0051", title = "管理员查询摇号数据导出", funcType = FuncTypeEnum.other ,checkPrivilege = BoolEnum.FALSE)
    public void exportEnrollLottery(EduStudentEnrollQueryVO vo, HttpServletResponse response) {
        ExcelVO excelVO = new ExcelVO();
        excelVO.setModelCode(vo.getModelCode());
        ExcelModelVO excelModelVO=excelIntegration.getModel(excelVO);

        String destFilePath = this.tempPath + "/" + IdUtil.fastSimpleUUID() + "." + excelModelVO.getExcelType();
        int pageNum=1;
        setDataEnrollLottery(excelModelVO,null,destFilePath,vo,pageNum);
        String fileName=vo.getFileName();
        if (StringUtils.isBlank(fileName)) {
            fileName =
                    excelModelVO.getModelName()
                            + "_"
                            + DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN)
                            + "."
                            + (StringUtils.isBlank(excelModelVO.getExcelType())
                            ? "xls"
                            : excelModelVO.getExcelType());
        }
        File file = FileUtil.file(destFilePath);
        BufferedInputStream in = null;
        try {
            in = FileUtil.getInputStream(file);
            ServletUtil.write(response, in, "application/octet-stream;charset=utf-8", fileName);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if(in!=null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            FileUtil.del(destFilePath);
        }
    }
    private void setDataEnrollLottery(ExcelModelVO excelModelVO, ExcelWriter excelWriter, String destFilePath, EduStudentEnrollQueryVO vo, int pageNum){
        vo.setPageNum(pageNum);
        vo.setPageSize(500);
        boolean closeFlag=false;
        try {
            PageInfo<EduStudentEnrollVO> pageInfo= this.getEnrollLotteryList(vo);
            String total=String.valueOf(pageInfo.getTotal());
            List<Object> list=new ArrayList<>();
            if(!CollectionUtils.isEmpty(pageInfo.getList())){
                for(EduStudentEnrollVO eduStudentEnrollVO:pageInfo.getList()){
                    list.add(eduStudentEnrollVO);
                }
            }
            if(pageNum==1){
                if(excelWriter==null){
                    excelWriter=excelCommonHelper.createExcelWriter(excelModelVO,destFilePath,Integer.parseInt(total));
                }
                excelCommonHelper.writeBean(excelWriter,list);
            }else{
                excelCommonHelper.writeBean(excelWriter,list);
            }
            if(pageInfo.isHasNextPage()){
                pageNum=pageNum+1;
                setDataEnrollLottery(excelModelVO,excelWriter,destFilePath,vo,pageNum);
            }else{
                closeFlag=true;
            }
        }catch (AppException appEx){
            throw appEx;
        }catch (Exception e){
            throw new AppException("调用自定义写入服务异常:" + e.getMessage());
        }finally {
            if(closeFlag&&excelWriter!=null){
                excelWriter.close();
            }
        }
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0060", title = "摇号导出人员缓存清除", funcType = FuncTypeEnum.query)
    public void clearEnrollLotteryCache(EduStudentEnrollQueryVO vo) {
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper = new QueryWrapper<>();
        if(StringUtils.isBlank(vo.getSchoolId())){
            vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        }
        //摇号数据只取审核通过待录取数据
        enrollQueryWrapper.lambda()
                .eq(EduStudentEnroll::getYear,vo.getYear())
                .eq(EduStudentEnroll::getSchoolId,vo.getSchoolId())
                .eq(!ObjectUtils.isEmpty(vo.getFatherIdcard()),EduStudentEnroll::getFatherIdcard,vo.getFatherIdcard())
                .eq(!ObjectUtils.isEmpty(vo.getConfigTypeName()),EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .eq(!ObjectUtils.isEmpty(vo.getAspirationType()),EduStudentEnroll::getAspirationType,vo.getAspirationType())
                .eq(!ObjectUtils.isEmpty(vo.getFollowingFlag()),EduStudentEnroll::getFollowingFlag,vo.getFollowingFlag())
                .eq(EduStudentEnroll::getEnrollStatus,"1")
                .orderByAsc(EduStudentEnroll::getSerialNum);
        List<EduStudentEnroll> list = eduStudentEnrollService.list(enrollQueryWrapper);

        for (EduStudentEnroll enroll : list) {
            eduEnrollClearCacheHelper.clearCacheMyEnroll(enroll.getIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnroll(enroll.getFatherIdcard());
            eduEnrollClearCacheHelper.clearCacheMyEnroll(enroll.getMotherIdcard());

        }
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0061", title = "义务段正式报名管理缓存清除", funcType = FuncTypeEnum.query)
    public void clearYwEnrollCache(EduStudentEnrollQueryVO vo) {
        int pageNum = 1;
        vo.setPageNum(pageNum);
        if(StringUtils.isBlank(vo.getSchoolId())){
            vo.setSchoolId(SessionUtil.getSessionInfo().getOrgId());
        }
        vo.setPageSize(500);

        PageInfo<EduStudentEnrollVO> pageInfo = this.getList(vo);
        if(!CollectionUtils.isEmpty(pageInfo.getList())){
            for (EduStudentEnrollVO enrollVO : pageInfo.getList()) {
                eduEnrollClearCacheHelper.clearCacheMyEnroll(enrollVO.getIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnroll(enrollVO.getFatherIdcard());
                eduEnrollClearCacheHelper.clearCacheMyEnroll(enrollVO.getMotherIdcard());
            }
        }

        if(pageInfo.isHasNextPage()){
            vo.setPageNum(pageNum+1); ;
            clearYwEnrollCache(vo);
        }
    }

    @Override
    @OpApi(funcCode = "eduStudentEnroll0062", title = "学生线下录入学生修改", funcType = FuncTypeEnum.query)
    @Transactional
    public EduStudentEnrollVO editStudentEnrollBySchool(SaveStudentEnrollVO vo) {
        String studentEnrollId = vo.getStudentEnrollId();
        if (ObjectUtils.isEmpty(studentEnrollId)){
            throw new AppException("报名主键不能为空！");
        }
        EduStudentEnroll eduStudentEnroll = eduStudentEnrollService.getById(studentEnrollId);
        if (ObjectUtils.isEmpty(eduStudentEnroll)){
            throw new AppException("数据不存在，请刷新后重试！");
        }
        //修改前参数校验
        saveCheckStudentEnroll(vo);
        Integer year = eduHelper.thisYear();
        //时间控制
        //判断是否在年度招生时间中
        EduOperationCacheQueryVO queryVO=new EduOperationCacheQueryVO();
        queryVO.setClassify("2");
        queryVO.setAreaCode(eduStudentEnroll.getAreaCode());
        queryVO.setYear(year);
        EduOperationCacheVO eduOperationCacheVO=eduSystemConfigIntegration.getEduOperation(queryVO);
        if(eduOperationCacheVO==null){
            throw new AppException("本年度义务教育阶段招生参数未配置，请联系系统管理员");
        }
        Map<String, EduOperationCacheDetailVO> operation=eduOperationCacheVO.getOperation();
        EduOperationCacheDetailVO xxOperation=operation.get("YW023");//学校录入时间
        if(xxOperation==null){
            throw new AppException(year+"年度义务段学校线下报名录入工作尚未开始");
        }
        if(!xxOperation.isFlag()){
            if ("1".equalsIgnoreCase(xxOperation.getType()) || "3".equalsIgnoreCase(xxOperation.getType())) {
                throw new AppException(year+"年度义务段学校线下报名录入工作尚未开始");
            }else{
                throw new AppException(year+"年度义务段学校线下报名录入工作已结束");
            }
        }

        //1.修改当前学校的报名信息
        eduStudentEnrollService.update(Wrappers.<EduStudentEnroll>lambdaUpdate()
                .eq(EduStudentEnroll::getStudentEnrollId,studentEnrollId)
                .set(EduStudentEnroll::getIdcard,vo.getIdcard())
                .set(EduStudentEnroll::getCardType,vo.getCardType())
                .set(EduStudentEnroll::getFullName,vo.getFullName())
                .set(EduStudentEnroll::getSex,vo.getSex())
                .set(EduStudentEnroll::getHouseholdPlace,vo.getHouseholdPlace())
                .set(!ObjectUtils.isEmpty(vo.getConfigTypeName()),EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                .set(!ObjectUtils.isEmpty(vo.getFormId()),EduStudentEnroll::getFormId,vo.getFormId())
                .set(EduStudentEnroll::getRemarks,vo.getRemarks())
                .set(EduStudentEnroll::getParam20,vo.getParam20())
                .set(!ObjectUtils.isEmpty(vo.getBirthYmd()),EduStudentEnroll::getBirthYmd,vo.getBirthYmd())
                .set(!ObjectUtils.isEmpty(vo.getFatherIdcard()),EduStudentEnroll::getFatherIdcard,vo.getFatherIdcard())
                .set(!ObjectUtils.isEmpty(vo.getFatherCardType()),EduStudentEnroll::getFatherCardType,vo.getFatherCardType())
                .set(!ObjectUtils.isEmpty(vo.getFatherName()),EduStudentEnroll::getFatherName,vo.getFatherName())
                .set(!ObjectUtils.isEmpty(vo.getMotherCardType()),EduStudentEnroll::getMotherCardType,vo.getMotherCardType())
                .set(!ObjectUtils.isEmpty(vo.getMotherIdcard()),EduStudentEnroll::getMotherIdcard,vo.getMotherIdcard())
                .set(!ObjectUtils.isEmpty(vo.getMotherName()),EduStudentEnroll::getMotherName,vo.getMotherName())
                .set(!ObjectUtils.isEmpty(vo.getFatherCellphone()),EduStudentEnroll::getFatherCellphone,vo.getFatherCellphone())
                .set(!ObjectUtils.isEmpty(vo.getMotherCellphone()),EduStudentEnroll::getMotherCellphone,vo.getMotherCellphone())
                .set(!ObjectUtils.isEmpty(vo.getAddress()),EduStudentEnroll::getAddress,vo.getAddress())
        );

        //2.修改预采集信息，根据身份证进行查询
        QueryWrapper<EduStudentEnrollPre> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda()
                .eq(EduStudentEnrollPre::getIdcard,eduStudentEnroll.getIdcard())
                .eq(EduStudentEnrollPre::getYear,eduStudentEnroll.getYear())
                .eq(EduStudentEnrollPre::getAuthStatus,AuthStatusEnum.YES.getType());
        List<EduStudentEnrollPre> eduStudentEnrollPres = eduStudentEnrollPreService.list(queryWrapper);
        if (!CollectionUtils.isEmpty(eduStudentEnrollPres)){
            for (EduStudentEnrollPre eduStudentEnrollPre : eduStudentEnrollPres) {
                eduStudentEnrollPreService.update(Wrappers.<EduStudentEnrollPre>lambdaUpdate()
                        .eq(EduStudentEnrollPre::getStudentEnrollPreId,eduStudentEnrollPre.getStudentEnrollPreId())
                        .set(EduStudentEnrollPre::getIdcard,vo.getIdcard())
                        .set(EduStudentEnrollPre::getCardType,vo.getCardType())
                        .set(EduStudentEnrollPre::getFullName,vo.getFullName())
                        .set(!ObjectUtils.isEmpty(vo.getFatherIdcard()),EduStudentEnrollPre::getFatherIdcard,vo.getFatherIdcard())
                        .set(!ObjectUtils.isEmpty(vo.getFatherCardType()),EduStudentEnrollPre::getFatherCardType,vo.getFatherCardType())
                        .set(!ObjectUtils.isEmpty(vo.getFatherName()),EduStudentEnrollPre::getFatherName,vo.getFatherName())
                        .set(!ObjectUtils.isEmpty(vo.getMotherCardType()),EduStudentEnrollPre::getMotherCardType,vo.getMotherCardType())
                        .set(!ObjectUtils.isEmpty(vo.getMotherIdcard()),EduStudentEnrollPre::getMotherIdcard,vo.getMotherIdcard())
                        .set(!ObjectUtils.isEmpty(vo.getMotherName()),EduStudentEnrollPre::getMotherName,vo.getMotherName())
                );
            }
        }

        //修改家庭表信息
        List<String> preIds = eduStudentEnrollPres.stream().map(EduStudentEnrollPre::getStudentEnrollPreId).distinct().collect(Collectors.toList());
        QueryWrapper<EduStudentEnrollFamily> familyQueryWrapper = new QueryWrapper<>();
        familyQueryWrapper.lambda().in(EduStudentEnrollFamily::getStudentEnrollPreId,preIds);
        List<EduStudentEnrollFamily> familyList = eduStudentEnrollFamilyService.list(familyQueryWrapper);
        if (CollectionUtil.isNotEmpty(familyList)){
            for (EduStudentEnrollFamily eduStudentEnrollFamily : familyList) {
                //父亲
                if (eduStudentEnrollFamily.getRelationshipType().equals(RelationTypeEnum.father.getType())){
                    eduStudentEnrollFamilyService.update(Wrappers.<EduStudentEnrollFamily>lambdaUpdate()
                            .eq(EduStudentEnrollFamily::getStudentPreFamilyId,eduStudentEnrollFamily.getStudentPreFamilyId())
                            .set(!ObjectUtils.isEmpty(vo.getFatherIdcard()),EduStudentEnrollFamily::getIdcard,vo.getFatherIdcard())
                            .set(!ObjectUtils.isEmpty(vo.getFatherCardType()),EduStudentEnrollFamily::getCardType,vo.getFatherCardType())
                            .set(!ObjectUtils.isEmpty(vo.getFatherName()),EduStudentEnrollFamily::getFullName,vo.getFatherName())
                    );
                }else if (RelationTypeEnum.mother.getType().equals(eduStudentEnrollFamily.getRelationshipType())){
                    eduStudentEnrollFamilyService.update(Wrappers.<EduStudentEnrollFamily>lambdaUpdate()
                            .eq(EduStudentEnrollFamily::getStudentPreFamilyId,eduStudentEnrollFamily.getStudentPreFamilyId())
                            .set(!ObjectUtils.isEmpty(vo.getMotherIdcard()),EduStudentEnrollFamily::getIdcard,vo.getMotherIdcard())
                            .set(!ObjectUtils.isEmpty(vo.getMotherCardType()),EduStudentEnrollFamily::getCardType,vo.getMotherCardType())
                            .set(!ObjectUtils.isEmpty(vo.getMotherName()),EduStudentEnrollFamily::getFullName,vo.getMotherName())
                    );
                }

            }

        }

        eduEnrollClearCacheHelper.clearCacheMyEnroll(eduStudentEnroll.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(eduStudentEnroll.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(eduStudentEnroll.getMotherIdcard());
        return Convert.convert(EduStudentEnrollVO.class, vo);
    }
    /**
     * 义务端学校录入报名人员保存校验
     * @param vo
     */
    private void saveCheckStudentEnroll(SaveStudentEnrollVO vo) {
        if (StringUtils.isBlank(vo.getConfigTypeName()) && StringUtils.isBlank(vo.getConfigName())) {
            throw new AppException("报名类别不能为空");
        }
        if (StringUtils.isBlank(vo.getRemarks())) {
            throw new AppException("请输入录取依据");
        }
        if (StringUtils.isBlank(vo.getParam20())) {
            throw new AppException("必须传入佐证资材料");
        }
        boolean xsFlag = IdcardUtil.isValidCard(vo.getIdcard());
        if (vo.getCardType().equals(CardTypeEnum.idcard.getType()) && !xsFlag) {
            throw new AppException("学生身份证有误！");
        } else {
            if (xsFlag && !CardTypeEnum.idcard.getType().equals(vo.getCardType())) {
                throw new AppException("学生证件类型，请选择身份证！");
            }
            vo.setIdcard(vo.getIdcard().trim().toUpperCase());
        }
        if (StringUtils.isBlank(vo.getMotherCardType())) {
            vo.setMotherCardType(CardTypeEnum.idcard.getType());
        }
        if (StringUtils.isBlank(vo.getFatherCardType())) {
            vo.setFatherCardType(CardTypeEnum.idcard.getType());
        }

        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        boolean flag = true;
        if (!ObjectUtils.isEmpty(vo.getMotherIdcard())) {
            boolean motherFlag = IdcardUtil.isValidCard(vo.getMotherIdcard());
            if (CardTypeEnum.idcard.getType().equals(vo.getMotherCardType()) && !motherFlag) {
                throw new AppException("母亲身份证有误！");
            } else {
                if (motherFlag && !CardTypeEnum.idcard.getType().equals(vo.getMotherCardType())) {
                    throw new AppException("母亲证件类型，请选择身份证！");
                }
                vo.setMotherIdcard(vo.getMotherIdcard().trim().toUpperCase());
            }
            if (ObjectUtils.isEmpty(vo.getMotherName())) {
                throw new AppException("母亲姓名不能为空！");
            } else {
                vo.setMotherName(
                        Validator.isChinese(vo.getMotherName())
                                ? vo.getMotherName().replace(" ", "").trim()
                                : vo.getMotherName().trim());
            }
            flag = false;
        }

        if (!ObjectUtils.isEmpty(vo.getFatherIdcard())) {
            boolean fatherFlag = IdcardUtil.isValidCard(vo.getFatherIdcard());
            if (CardTypeEnum.idcard.getType().equals(vo.getFatherCardType()) && !fatherFlag) {
                throw new AppException("父亲(监护人)身份证有误！");
            } else {
                if (fatherFlag && !CardTypeEnum.idcard.getType().equals(vo.getFatherCardType())) {
                    throw new AppException("父亲(监护人)证件类型，请选择身份证！");
                }
                vo.setFatherIdcard(vo.getFatherIdcard().trim().toUpperCase());
            }
            if (ObjectUtils.isEmpty(vo.getFatherName())) {
                throw new AppException("父亲(监护人)姓名不能为空！");
            } else {
                vo.setFatherName(
                        Validator.isChinese(vo.getFatherName())
                                ? vo.getFatherName().replace(" ", "").trim()
                                : vo.getFatherName().trim());
            }
            flag = false;
        }
        if (ObjectUtils.isEmpty(vo.getFullName())) {
            throw new AppException("学生姓名不能为空！");
        } else {
            vo.setFullName(
                    Validator.isChinese(vo.getFullName())
                            ? vo.getFullName().replace(" ", "").trim()
                            : vo.getFullName().trim());
        }
        if (flag) {
            throw new AppException("父亲（监护人）或母亲一方必填");
        }

        if (xsFlag) {
            if (StringUtils.isBlank(vo.getBirthYmd())) {
                vo.setBirthYmd(IdcardUtil.getBirth(vo.getIdcard()));
            }
            if (StringUtils.isBlank(vo.getSex())) {
                int gender = IdcardUtil.getGenderByIdCard(vo.getIdcard());
                if (gender == 1) {
                    // 男
                    vo.setSex("1");
                } else {
                    // 女
                    vo.setSex("2");
                }
            }
        }

    }

    public PageInfo<EduStudentEnrollVO> getEnrollLotteryList(EduStudentEnrollQueryVO vo) {
        if(StringUtils.isEmpty(vo.getConfigTypeName())){
            throw new AppException("请先在查询类别中选择报名类别");
        }
        // 开启分页
        if (vo.getPageNum() != null && vo.getPageSize() != null) {
            PageHelper.startPage(vo.getPageNum(), vo.getPageSize());
        }
        List<EduStudentEnrollVO> list = eduStudentEnrollService.getEnrollLotteryList(vo);

        if (CollectionUtils.isEmpty(list)) {
            // 判断是否为空，为空则返回空参数
            return PagerUtil.createEmptyPagerInfo(vo.getPageNum(), vo.getPageSize());
        }
        // 不为空则获取分页结果
        PageInfo<EduStudentEnrollVO> pageInfo = new PageInfo<>(list);
        // 返回参数需要通过common层的vo实体类，用该方法可以批量转换
        List<EduStudentEnrollVO> resultList = pageInfo.getList();

        for (EduStudentEnrollVO eduStudentEnrollVO : resultList) {
            eduStudentEnrollVO.setFullNameTm(getFullName(eduStudentEnrollVO.getFullName()));
            eduStudentEnrollVO.setIdcardTm(getIdcard(eduStudentEnrollVO.getIdcard()));
            if("1".equals(eduStudentEnrollVO.getBindMianFlag())) {
                QueryWrapper<EduStudentEnroll> enrollQueryWrapper = new QueryWrapper<>();
                enrollQueryWrapper.lambda().eq(EduStudentEnroll::getYear, vo.getYear())
                        .eq(EduStudentEnroll::getSchoolId, vo.getSchoolId())
                        .eq(EduStudentEnroll::getConfigTypeName,vo.getConfigTypeName())
                        .eq(EduStudentEnroll::getEnrollStatus, vo.getEnrollStatus())
                        .eq(EduStudentEnroll::getBindMianFlag,"0")
                        .eq(EduStudentEnroll::getBindIdcard, eduStudentEnrollVO.getIdcard());
                List<EduStudentEnroll> enrollList = eduStudentEnrollService.list(enrollQueryWrapper);
                if (!CollectionUtils.isEmpty(enrollList)) {
                    for (EduStudentEnroll enroll : enrollList) {
                        eduStudentEnrollVO.setApplyId(eduStudentEnrollVO.getApplyId()+","+enroll.getApplyId());
                        eduStudentEnrollVO.setFullName(eduStudentEnrollVO.getFullName()+","+enroll.getFullName());
                        eduStudentEnrollVO.setIdcard(eduStudentEnrollVO.getIdcard()+","+enroll.getIdcard());
                        eduStudentEnrollVO.setFullNameTm(eduStudentEnrollVO.getFullNameTm()+","+getFullName(enroll.getFullName()));
                        eduStudentEnrollVO.setIdcardTm(eduStudentEnrollVO.getIdcardTm()+","+getIdcard(enroll.getIdcard()));
                    }
                }
            }
        }

        return PagerUtil.parsePagerVo(resultList, pageInfo);
    }



    private String getFullName(String str){
        if(StringUtils.isBlank(str)){
            return str;
        }
        if(str.length()<3){
            return str.substring(0,1)+"*";
        }else{
            int le=str.length()-1;
            return str.substring(0,1)+"*"+str.substring(le);
        }

    }
    //证件号码脱敏
    private String getIdcard(String str){
        if(StringUtils.isBlank(str)){
            return str;
        }
        if (str.length()==18) {
            return str.substring(0,6)+"********"+str.substring(14,18);
        }else{
            int len=str.length();
            String  enCard=str.substring(0, 2);
            for(int i=0;i<len-4;i++){
                enCard=enCard+"*";
            }
            enCard=enCard+str.substring(len-3);
            return enCard;
        }
    }
    private void setPersonId(EduStudentEnroll enroll) {
        PersonInfo stuPersonInfo =
                this.savePerson(enroll.getIdcard(), enroll.getCardType(), enroll.getFullName());
        if (!ObjectUtils.isEmpty(enroll.getMotherIdcard())) {
            PersonInfo moPersonInfo =
                    this.savePerson(
                            enroll.getMotherIdcard(), enroll.getMotherCardType(), enroll.getMotherName());
        }
        if (!ObjectUtils.isEmpty(enroll.getFatherIdcard())) {
            PersonInfo faPersonInfo =
                    this.savePerson(
                            enroll.getFatherIdcard(), enroll.getFatherCardType(), enroll.getFatherName());
        }
    }

    private PersonInfo savePerson(String idcard, String cardType, String fullName) {
        if (StringUtils.isBlank(cardType)) {
            cardType = CardTypeEnum.idcard.getType();
        }
        if(!com.bifang.module.system.common.enums.CardTypeEnum.idcard.getType().equalsIgnoreCase(cardType)){
            if(IdcardUtil.isValidCard(idcard)){
                cardType= com.bifang.module.system.common.enums.CardTypeEnum.idcard.getType();
            }
        }
        PersonInfo personInfo =  personInfoService.selectByCardTypeAndIdcard(cardType, StringUtils.upperCase(idcard));
        if (personInfo == null) {
            QueryWrapper<PersonInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().eq(PersonInfo::getIdcard, idcard);
            List<PersonInfo> list = personInfoService.list(queryWrapper);
            if (!CollectionUtils.isEmpty(list)) {
                personInfo = list.get(0);
            }
        }
        if (ObjectUtils.isEmpty(personInfo)) {
            personInfo = new PersonInfo();
            personInfo.setIdcard(StringUtils.upperCase(idcard));
            personInfo.setFullName(fullName);
            personInfo.setCardType(cardType);
            return personInfoService.addPerson(personInfo);
        } else {
            if (!personInfo.getFullName().equals(fullName)||!personInfo.getCardType().equals(cardType)) {
                personInfo.setFullName(fullName);
                personInfo.setCardType(cardType);
                personInfoService.updateById(personInfo);
            }
            return personInfo;
        }
    }

    private  String getApplyId(Integer year,String schoolNature,String schoolNum,Integer orderNo,String shcoolId,Integer count){
        if(count==null){
            count=count+1;
        }
        if(count>10){
            //超过10次未能比对到不重复的数据，返回报错
            throw new AppException("系统繁忙，请重新点提交");
        }
        String y=year % 100+"";
        String num = StringUtils.leftPad(schoolNum, 3, "0");
        String orderNoId = StringUtils.leftPad(orderNo + "", 2, "0");
        String applyId=y+num+orderNoId;
        if("0".equals(schoolNature)){
            String redisKey="ywEnroll:gb:"+shcoolId+":"+orderNo;
            if(redisHelper.hasKey(redisKey)) {
                String redisApplyId= (String) redisHelper.get(redisKey);
                applyId=String.valueOf(Long.parseLong(redisApplyId)+1);
                redisHelper.set(redisKey,applyId,86400);
            }else{
                //公办
                String max=eduStudentEnrollService.queryMaxApplyId(applyId,shcoolId,year);
                if(StringUtils.isBlank(max)){
                    applyId=applyId+StringUtils.leftPad("1", 3, "0");
                }else{
                    applyId=String.valueOf(Long.parseLong(max)+1);
                }
                redisHelper.set(redisKey,applyId,86400);
            }
            return applyId;
        }else{
            //民办或者公参民转公
            String redisKey="ywEnroll:mb:"+shcoolId+":"+orderNo;
            Integer randomId =null;
            if(redisHelper.hasKey(redisKey)) {

                List<Integer> randomList= (List<Integer>) redisHelper.get(redisKey);
                if(CollectionUtils.isEmpty(randomList)){
                    Integer[] randomNums= NumberUtil.generateBySet(1,9999,3000);
                    randomList=Arrays.stream(randomNums).distinct().collect(Collectors.toList());
                    randomId=randomList.get(0);
                    randomList.remove(randomId);
                    redisHelper.set(redisKey,randomList,259200);
                }else{
                    randomId=randomList.get(0);
                    randomList.remove(randomId);
                    redisHelper.set(redisKey,randomList,259200);
                }

            }else{
                Integer[] randomNums=NumberUtil.generateBySet(1,9999,3000);
                List<Integer> randomList=Arrays.stream(randomNums).distinct().collect(Collectors.toList());
                randomId=randomList.get(0);
                randomList.remove(randomId);
                redisHelper.set(redisKey,randomList,259200);
            }

            applyId=applyId+StringUtils.leftPad(randomId + "", 4, "0");

        }
        QueryWrapper<EduStudentEnroll> queryWrapper=new QueryWrapper<>();
        queryWrapper.lambda().select(EduStudentEnroll::getStudentEnrollId).eq(EduStudentEnroll::getSchoolId,shcoolId)
                .eq(EduStudentEnroll::getYear,year)
                .eq(EduStudentEnroll::getApplyId,applyId);
        if(eduStudentEnrollService.count(queryWrapper)>0){
            applyId=this.getApplyId(year,schoolNature,schoolNum,orderNo,shcoolId,count);
        }
        return applyId;

    }


    private void auth(StudentEnrollSaveVO vo){
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getAuthStatus())) {
            throw new AppException("审核状态不能为空");
        }
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }



        EduStudentEnroll old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被回退，请重新查询");
        }

        int year;
        year = eduHelper.thisYear();

        if (old.getYear() < year) {
            throw new AppException("历年报名数据不允许审核");
        }


        //业务期判断
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setSchoolId(old.getSchoolId());
        checkShLqVO.setYear(old.getYear());

        if("0".equals(old.getSchoolNature())||"2".equals(old.getSchoolNature())) {
            checkShLqVO.setOpType(old.getSchoolNature());
        }
        if("1".equals(old.getSchoolNature())){
            if("1".equals(old.getAspirationType())){
                //民办1
                checkShLqVO.setOpType("1");
            }
            if("2".equals(old.getAspirationType())){
                //民办2
                checkShLqVO.setOpType("3");
            }
            if("3".equals(old.getAspirationType())){
                //民办3
                checkShLqVO.setOpType("4");
            }

        }
        checkSh(checkShLqVO);

        if (!AuthStatusEnum.NODO.getType().equals(old.getAuthStatus())) {
            throw new AppException(old.getFullName() + "的报名数据已审核，请重新查询");
        }
        if (!old.getSchoolId().equals(SessionUtil.getSessionInfo().getOrgId())) {
            throw new AppException("报名学校和审核学校不一致，请联系管理员查找原因");
        }

        QueryWrapper<EduEnrollmenBrochure> queryBrochureWrapper = new QueryWrapper<>();
        queryBrochureWrapper.lambda().eq(EduEnrollmenBrochure::getYear, old.getYear())
                .eq(EduEnrollmenBrochure::getSchoolId, old.getSchoolId());
        EduEnrollmenBrochure eduEnrollmenBrochure = eduEnrollmenBrochureService.getOne(queryBrochureWrapper, false);
        if (eduEnrollmenBrochure == null) {
            throw new AppException("未找到招生方案信息");
        }
        /*政策调整：*/
//        if ("2".equals(old.getAspirationType())) {
//            //第二志愿需要第一志愿停止后才能审核
//            if (SpecialStringUtils.isBlank(eduEnrollmenBrochure.getEndRegistration()) || "0".equals(eduEnrollmenBrochure.getEndRegistration())) {
//                throw new AppException("第一志愿未停止招生，不能进行第二志愿的审核工作");
//            }
//        }
//        if ("3".equals(old.getAspirationType())) {
//            //第二志愿需要第一志愿停止后才能审核
//            if (SpecialStringUtils.isBlank(eduEnrollmenBrochure.getEndRegistration2()) || "0".equals(eduEnrollmenBrochure.getEndRegistration2())) {
//                throw new AppException("第二志愿未停止招生，不能进行第三志愿的审核工作");
//            }
//        }
        if ("1".equals(old.getSchoolNature())) {
            //民办
            if ("1".equals(old.getAspirationType())) {
                if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
                    throw new AppException("第一志愿招生已停止，不能审核");
                }
            } else if ("2".equals(old.getAspirationType())) {
                if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())) {
                    throw new AppException("第二志愿招生已停止，不能审核");
                }
            } else if ("3".equals(old.getAspirationType())) {
                if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())) {
                    throw new AppException("第三志愿招生已停止，不能审核");
                }
            } else if ("4".equals(old.getAspirationType())) {
                if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())) {
                    throw new AppException("第四志愿招生已停止，不能审核");
                }
            } else {
                if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
                    throw new AppException("招生已停止，不能审核");
                }
            }
        } else {
            if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
                throw new AppException("招生已停止，不能审核");
            }
        }
        List<String> enrollStatusList = new ArrayList<>();
        enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
        enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
        QueryWrapper<EduStudentEnroll> enrollQueryWrapper = new QueryWrapper<>();
        enrollQueryWrapper.lambda().select(EduStudentEnroll::getStudentEnrollId)
                .eq(EduStudentEnroll::getIdcard, old.getIdcard())
                .in(EduStudentEnroll::getEnrollStatus, enrollStatusList)
                .ne(EduStudentEnroll::getSchoolId, old.getSchoolId());
        if (eduStudentEnrollService.count(enrollQueryWrapper) > 0) {
            throw new AppException(old.getFullName() + "，其他学校待录取或者已录取");
        }
        old.setAuthStatus(vo.getAuthStatus());
        old.setAuthTime(new Date());
        old.setAuthRemarks(vo.getAuthRemarks());
        old.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
        if (AuthStatusEnum.NO.getType().equals(vo.getAuthStatus())) {
            old.setAdmitFlag(BoolEnum.FALSE.getType());
            old.setAuthRemarks(vo.getAuthRemarks());
            old.setAdmitTime(old.getAuthTime());
            old.setAdmitUserId(SessionUtil.getSessionInfo().getUserId());
            old.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
        } else {
            // 调用金华接口判断是否已录取
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("localLqDw");
            commonVO.setAreaCode(vo.getAreaCode());
            String localDw = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(localDw)) {
                throw new AppException("请先配置金华教育本地录取单位");
            }
//            // 调用金华接口判断是否已录取
//            EduJhjyQuerySyncVO eduJhjyQuerySyncVO = eduJhjyQuerySyncIntegration.queryJhjy(old);
//            if (StringUtils.isNotBlank(eduJhjyQuerySyncVO.getLqDw()) && !localDw.equals(eduJhjyQuerySyncVO.getLqDw())) {
//                throw new AppException("学生(" + old.getFullName() + ")已被" + eduJhjyQuerySyncVO.getLqDw() + "录取，请联系基教科处理");
//            }
            EduStudentEnrollVO queryVO = Convert.convert(EduStudentEnrollVO.class, old);
            EduDyjyQuerySyncVO eduDyjyQuerySyncVO = dyjyQuerySyncIntegration.querySyncInfo(queryVO);
            if (StringUtils.isNotBlank(eduDyjyQuerySyncVO.getLqDw()) && !localDw.equals(eduDyjyQuerySyncVO.getLqDw())) {
                throw new AppException("学生(" + old.getFullName() + ")已被" + eduDyjyQuerySyncVO.getLqDw() + "录取，请联系基教科处理");
            }

            if ("0".equals(old.getSchoolNature())) {
                //公办
                QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().select(EduStudentEnroll::getStudentEnrollId)
                        .eq(EduStudentEnroll::getParentId, old.getStudentEnrollId())
                        .eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType());
                if (eduStudentEnrollService.count(queryWrapper) > 0) {
                    throw new AppException(old.getFullName() + "，其他学校待审核，请联系电教馆查询民办和“公参民”转公是否结束招生");
                }
            } else if ("1".equals(old.getSchoolNature())) {
                //民办
                QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                queryWrapper.lambda().select(EduStudentEnroll::getStudentEnrollId)
                        .eq(EduStudentEnroll::getIdcard, old.getIdcard())
                        .eq(EduStudentEnroll::getSchoolNature, "2")
                        .eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType());
                if (eduStudentEnrollService.count(queryWrapper) > 0) {
                    throw new AppException(old.getFullName() + "，其他学校待审核，请联系电教馆查询“公参民”转公是否结束招生");
                }
            }
            old.setEnrollStatus(EnrollStatusFormalEnum.dlq.getType());
        }
        eduStudentEnrollService.updateById(old);
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getFatherIdcard());
        eduEnrollClearCacheHelper.clearCacheMyEnroll(old.getMotherIdcard());
    }

    @Override
    public void checkSh(EnrollCheckShLqVO vo) {
        if (vo.getYear() == null) {
            throw new AppException("年度不能为空");
        }
        if (StringUtils.isBlank(vo.getOpType())) {
            throw new AppException("操作类型不能为空");
        }


        int year = eduHelper.thisYear();

        if (vo.getYear() < year) {
            throw new AppException("招生审核工作已结束，不能审核");
        } else if (vo.getYear() > year) {
            throw new AppException("招生审核工作尚未开始，不能审核");
        }
       // EduEnrollPlan eduEnrollPlan = enrollPlanIntegration.getByYear(year);
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class,vo);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if (eduOperationCacheVO.getOperation() == null) {
            throw new AppException(year + "年度招生计划参数不存在");
        }
        Long current = DateUtil.currentSeconds();
        if ("0".equals(vo.getOpType())) {
            //公办
            String schoolId = vo.getSchoolId();
            if (StringUtils.isNotBlank(schoolId)) {
                schoolId = SessionUtil.getSessionInfo().getOrgId();
            }
            QueryWrapper<EduAuthSchool> authSchoolQueryWrapper = new QueryWrapper<>();
            authSchoolQueryWrapper.lambda().eq(EduAuthSchool::getSchoolId, schoolId)
                    .eq(EduAuthSchool::getYear, year);
            if (eduAuthSchoolService.count(authSchoolQueryWrapper) > 0) {
                //城区学校
                if (eduOperationCacheVO.getOperation().get("YW003")  == null) {
                    throw new AppException("招生审核工作尚未开始，不能审核");
                } else {
                    if(!eduOperationCacheVO.getOperation().get("YW003").isFlag()){
                        throw new AppException(eduOperationCacheVO.getOperation().get("YW003").getMessagePrompts()+eduOperationCacheVO.getOperation().get("YW003").getMessageTip());
                    }
                }
            } else {
                //其他学校
                if (eduOperationCacheVO.getOperation().get("YW020")  == null) {
                    throw new AppException("招生审核工作尚未开始，不能审核");
                } else {
                    if(!eduOperationCacheVO.getOperation().get("YW020").isFlag()){
                        throw new AppException(eduOperationCacheVO.getOperation().get("YW020").getMessagePrompts()+eduOperationCacheVO.getOperation().get("YW020").getMessageTip());
                    }
                }
            }

        } else if ("1".equals(vo.getOpType())) {
            //民办1
            if (eduOperationCacheVO.getOperation().get("YW007")  == null) {
                throw new AppException("招生审核工作尚未开始，不能审核");
            } else {
                if(!eduOperationCacheVO.getOperation().get("YW007").isFlag()){
                    throw new AppException(eduOperationCacheVO.getOperation().get("YW007").getMessagePrompts()+eduOperationCacheVO.getOperation().get("YW007").getMessageTip());
                }
            }
        } else if ("2".equals(vo.getOpType())) {
            //民转公
            if (eduOperationCacheVO.getOperation().get("YW014")  == null) {
                throw new AppException("招生审核工作尚未开始，不能审核");
            } else {
                if(!eduOperationCacheVO.getOperation().get("YW014").isFlag()){
                    throw new AppException(eduOperationCacheVO.getOperation().get("YW014").getMessagePrompts()+eduOperationCacheVO.getOperation().get("YW014").getMessageTip());
                }
            }
        } else if ("3".equals(vo.getOpType())) {
            //民办2
            if (eduOperationCacheVO.getOperation().get("YW011")  == null) {
                throw new AppException("招生审核工作尚未开始，不能审核");
            } else {
                if(!eduOperationCacheVO.getOperation().get("YW011").isFlag()){
                    throw new AppException(eduOperationCacheVO.getOperation().get("YW011").getMessagePrompts()+eduOperationCacheVO.getOperation().get("YW011").getMessageTip());
                }
            }
        }else if("4".equals(vo.getOpType())){
            //民办3
            if (eduOperationCacheVO.getOperation().get("YW055")  == null) {
                throw new AppException("招生审核工作尚未开始，不能审核");
            } else {
                if(!eduOperationCacheVO.getOperation().get("YW055").isFlag()){
                    throw new AppException(eduOperationCacheVO.getOperation().get("YW011").getMessagePrompts()+eduOperationCacheVO.getOperation().get("YW011").getMessageTip());
                }
            }
        }
    }

    @Override
    public void checklq(EnrollCheckShLqVO vo) {
        if (vo.getYear() == null) {
            throw new AppException("年度不能为空");
        }
        if (StringUtils.isBlank(vo.getOpType())) {
            throw new AppException("操作类型不能为空");
        }


        int year = eduHelper.thisYear();


        if (vo.getYear() < year) {
            throw new AppException("招生录取工作已结束，不能录取");
        } else if (vo.getYear() > year) {
            throw new AppException("招生录取工作尚未开始，不能录取");
        }
       // EduEnrollPlan eduEnrollPlan = enrollPlanIntegration.getByYear(year);
        if(StringUtils.isBlank(vo.getAreaCode())){
            vo.setAreaCode(SessionUtil.getSessionInfo().getAreaCode());
        }
        EduOperationCacheQueryVO cacheQueryVO = Convert.convert(EduOperationCacheQueryVO.class,vo);
        cacheQueryVO.setClassify("2");
        EduOperationCacheVO eduOperationCacheVO = eduSystemConfigIntegration.getEduOperation(cacheQueryVO);
        if (eduOperationCacheVO.getOperation() == null) {
            throw new AppException(year + "年度招生计划参数不存在");
        }
        Long current = DateUtil.currentSeconds();
        if ("0".equals(vo.getOpType())) {
            //公办
            String schoolId = vo.getSchoolId();
            if (StringUtils.isNotBlank(schoolId)) {
                schoolId = SessionUtil.getSessionInfo().getOrgId();
            }
            QueryWrapper<EduAuthSchool> authSchoolQueryWrapper = new QueryWrapper<>();
            authSchoolQueryWrapper.lambda().eq(EduAuthSchool::getSchoolId, schoolId)
                    .eq(EduAuthSchool::getYear, year);
            if (eduAuthSchoolService.count(authSchoolQueryWrapper) > 0) {
                //城区学校
                if (eduOperationCacheVO.getOperation().get("YW004")  == null) {
                    throw new AppException("招生录取工作尚未开始，不能录取");
                } else {
                    if(!eduOperationCacheVO.getOperation().get("YW004").isFlag()){
                        throw new AppException("招生录取工作尚未开始，不能录取");
                    }
                }
            } else {
                //其他学校
                if (eduOperationCacheVO.getOperation().get("YW021")  == null) {
                    throw new AppException("招生录取工作尚未开始，不能录取");
                } else {
                    if(!eduOperationCacheVO.getOperation().get("YW021").isFlag()){
                        throw new AppException("招生录取工作尚未开始，不能录取");
                    }
                }
            }

        } else if ("1".equals(vo.getOpType())) {
            //民办1
            if (eduOperationCacheVO.getOperation().get("YW009")  == null) {
                throw new AppException("招生录取工作尚未开始，不能录取");
            } else {
                if(!eduOperationCacheVO.getOperation().get("YW009").isFlag()){
                    throw new AppException("招生录取工作尚未开始，不能录取");
                }
            }
        } else if ("2".equals(vo.getOpType())) {
            //民转公
            if (eduOperationCacheVO.getOperation().get("YW016")  == null) {
                throw new AppException("招生录取工作尚未开始，不能录取");
            } else {
                if(!eduOperationCacheVO.getOperation().get("YW016").isFlag()){
                    throw new AppException("招生录取工作尚未开始，不能录取");
                }
            }
        } else if ("3".equals(vo.getOpType())) {
            //民办2
            if (eduOperationCacheVO.getOperation().get("YW013")  == null) {
                throw new AppException("招生录取工作尚未开始，不能录取");
            } else {
                if(!eduOperationCacheVO.getOperation().get("YW013").isFlag()){
                    throw new AppException("招生录取工作尚未开始，不能录取");
                }
            }
        } else if ("4".equals(vo.getOpType())) {
            //民办3
            if (eduOperationCacheVO.getOperation().get("YW057") == null) {
                throw new AppException("招生录取工作尚未开始，不能录取");
            } else {
                if (!eduOperationCacheVO.getOperation().get("YW057").isFlag()) {
                    throw new AppException("招生录取工作尚未开始，不能录取");
                }
            }
        }
    }

    private StudentEnrollLqVO admit(StudentEnrollSaveVO vo){
        if (StringUtils.isBlank(vo.getStudentEnrollId())) {
            throw new AppException("报名id不能为空");
        }
        if (StringUtils.isBlank(vo.getAdmitFlag())) {
            throw new AppException("录取状态不能为空");
        }

        EduStudentEnroll old = eduStudentEnrollService.getById(vo.getStudentEnrollId());
        if (old == null) {
            throw new AppException("报名数据不存在，可能已被回退，请重新查询");
        }
        //业务期判断
        EnrollCheckShLqVO checkShLqVO = new EnrollCheckShLqVO();
        checkShLqVO.setSchoolId(old.getSchoolId());
        checkShLqVO.setYear(old.getYear());
        checkShLqVO.setOpType(old.getSchoolNature());
        checklq(checkShLqVO);
        if (StringUtils.isNotBlank(old.getAdmitFlag())) {
            throw new AppException(old.getFullName() + "的报名数据已操作，请重新查询");
        }
        if (!AuthStatusEnum.YES.getType().equals(old.getAuthStatus())) {
            throw new AppException(old.getFullName() + "的报名数据未审核通过，不能录取");
        }
        if (!old.getSchoolId().equals(SessionUtil.getSessionInfo().getOrgId())) {
            throw new AppException("报名学校和录取学校不一致，请联系管理员查找原因");
        }
        QueryWrapper<EduStudentEnroll> dshQuery = new QueryWrapper<>();
        dshQuery.lambda().eq(EduStudentEnroll::getYear, old.getYear())
                .eq(EduStudentEnroll::getSchoolId, old.getSchoolId())
                .eq(!"0".equals(old.getSchoolNature()), EduStudentEnroll::getConfigTypeName, old.getConfigTypeName())
                .eq("0".equals(old.getSchoolNature()), EduStudentEnroll::getConfigName, old.getConfigName())
                .eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.dsh.getType())
                .eq("1".equals(old.getSchoolNature()), EduStudentEnroll::getAspirationType, old.getAspirationType());
        if (eduStudentEnrollService.count(dshQuery) > 0) {
            throw new AppException("同一报名类别存在待审核数据，请全部审核后再录取");
        }

        //超过计划数不能录取
        QueryWrapper<EduSchoolConfig> configQueryWrapper = new QueryWrapper<>();
        configQueryWrapper.lambda().select(EduSchoolConfig::getEnrolment, EduSchoolConfig::getSerialNumEnd)
                .eq(EduSchoolConfig::getSchoolId, old.getSchoolId())
                .eq(EduSchoolConfig::getAuthStatus, AuthStatusEnum.YES.getType())
                .eq(EduSchoolConfig::getStatus, BoolEnum.TRUE.getType())
                .eq(EduSchoolConfig::getYear, old.getYear());
        if ("1".equals(old.getSchoolNature()) || "2".equals(old.getSchoolNature())) {
            QueryWrapper<EduEnrollmenBrochure> brochureQueryWrapper = new QueryWrapper<>();
            brochureQueryWrapper.lambda().eq(EduEnrollmenBrochure::getYear, old.getYear())
                    .eq(EduEnrollmenBrochure::getSchoolId, old.getSchoolId());
            EduEnrollmenBrochure eduEnrollmenBrochure = eduEnrollmenBrochureService.getOne(brochureQueryWrapper, false);
            if (eduEnrollmenBrochure == null) {
                throw new AppException("未找到招生方案信息");
            }
            if ("2".equals(old.getSchoolNature())) {
                if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
                    throw new AppException("招生已停止，不能录取");
                }
            } else if ("1".equals(old.getSchoolNature())) {
                if ("1".equals(old.getAspirationType())) {
                    if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
                        throw new AppException("第一志愿招生已停止，不能录取");
                    }
                } else if ("2".equals(old.getAspirationType())) {
                    if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration2())) {
                        throw new AppException("第二志愿招生已停止，不能录取");
                    }
                } else if ("3".equals(old.getAspirationType())) {
                    if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration3())) {
                        throw new AppException("第三志愿招生已停止，不能录取");
                    }
                } else if ("4".equals(old.getAspirationType())) {
                    if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration4())) {
                        throw new AppException("第四志愿招生已停止，不能录取");
                    }
                }
            } else {
                if (BoolEnum.TRUE.getType().equals(eduEnrollmenBrochure.getEndRegistration())) {
                    throw new AppException("招生已停止，不能录取");
                }
            }

            //民办
            configQueryWrapper.lambda().eq(EduSchoolConfig::getConfigTypeName, old.getConfigTypeName());
        }
        EduSchoolConfig eduSchoolConfig = eduSchoolConfigService.getOne(configQueryWrapper, false);
        StudentEnrollLqVO retVO = new StudentEnrollLqVO();
        //计划人数
        Integer enrolment = 0;
        if (eduSchoolConfig != null) {
            enrolment = eduSchoolConfig.getEnrolment() == null ? 0 : eduSchoolConfig.getEnrolment();
        }
        //摇号截止序号
        Integer serialNumEnd = 0;
        if (eduSchoolConfig != null) {
            serialNumEnd = eduSchoolConfig.getSerialNumEnd() == null ? 0 : eduSchoolConfig.getSerialNumEnd();
        }
        if (BoolEnum.TRUE.getType().equals(vo.getAdmitFlag())) {
            //已录取人数
            QueryWrapper<EduStudentEnroll> lqQuery = new QueryWrapper<>();
            lqQuery.lambda().eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.lq.getType())
                    .eq(EduStudentEnroll::getYear, old.getYear())
                    .eq(EduStudentEnroll::getAdmitFlag, BoolEnum.TRUE.getType())
                    .eq(EduStudentEnroll::getSchoolId, old.getSchoolId());
            if ("1".equals(old.getSchoolNature()) || "2".equals(old.getSchoolNature())) {
                //民办
                lqQuery.lambda().eq(EduStudentEnroll::getConfigTypeName, old.getConfigTypeName());
            }
            long lqCount = eduStudentEnrollService.count(lqQuery);
            if (lqCount >= enrolment) {
                throw new AppException("录取人数已到达计划人数，如还需录取，请联系基教科修改招生计划");
            }
            if ("1".equals(old.getSchoolNature()) || "2".equals(old.getSchoolNature())) {
                //民办或民转公
                if (old.getSerialNum() != null) {
                    QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                    queryWrapper.lambda().eq(EduStudentEnroll::getSchoolId, old.getSchoolId())
                            .lt(EduStudentEnroll::getSerialNum, old.getSerialNum())
                            .eq(EduStudentEnroll::getAuthStatus, AuthStatusEnum.YES.getType())
                            .eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.dlq.getType())
                            .eq(EduStudentEnroll::getConfigTypeName, old.getConfigTypeName())
                            .eq("1".equals(old.getSchoolNature()), EduStudentEnroll::getAspirationType, old.getAspirationType());
                    if (eduStudentEnrollService.count(queryWrapper) > 0) {
                        throw new AppException("请按摇号排序号顺序录取");
                    }
                    if (eduSchoolConfig == null || eduSchoolConfig.getSerialNumEnd() == null) {
                        throw new AppException("请先联系系统管理员配置录取的摇号排序号截止序号");
                    }
                    //判断摇号序号是否全部导入
                    if (old.getSerialNum() > eduSchoolConfig.getSerialNumEnd()) {
                        throw new AppException("该摇号人员已超出可录取的范围");
                    }
                    old.setAdmitFlag(BoolEnum.TRUE.getType());
                    if (StringUtils.isBlank(old.getAdmitRemarks())) {
                        old.setAdmitRemarks("摇号录取");
                    }
                }
            } else {
                //公办 需要按排序号，排序号高的优先录取 特殊通道不校验
                EduSchool eduSchool = eduSchoolService.getById(old.getSchoolId());
                if (eduSchool == null) {
                    throw new AppException("学校基础信息不存在，请联系系统管理员");
                }
                if (!BoolEnum.TRUE.getType().equals(eduSchool.getAuthOrderByNo())) {
                    if (!BoolEnum.TRUE.getType().equals(old.getSpecialFlag())) {
                        QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
                        queryWrapper.lambda().eq(EduStudentEnroll::getYear, old.getYear())
                                .eq(EduStudentEnroll::getSchoolId, old.getSchoolId())
                                .lt(EduStudentEnroll::getConfigName, old.getConfigName())
                                .eq(EduStudentEnroll::getEnrollStatus, EnrollStatusFormalEnum.dlq.getType());
                        if (eduStudentEnrollService.count(queryWrapper) > enrolment) {
                            throw new AppException("请按报名类别的排序号的顺序录取，比如A类全部录取完才能录取B类");
                        }
                    }
                }

            }
            retVO.setLqCnt((int) lqCount);
        }

        retVO.setJhCnt(enrolment);

        old.setAdmitFlag(vo.getAdmitFlag());
        old.setAdmitRemarks(vo.getAdmitRemarks());
        old.setAdmitTime(new Date());
        old.setAdmitUserId(SessionUtil.getSessionInfo().getUserId());
        boolean sendFlag = true;
        if (BoolEnum.TRUE.getType().equals(vo.getAdmitFlag())) {
            CommonVO commonVO = new CommonVO();
            commonVO.setParamKey("localLqDw");
            commonVO.setAreaCode(old.getAreaCode());
            String localDw = commonIntegration.getValueByKeyAndArea(commonVO);
            if (StringUtils.isBlank(localDw)) {
                throw new AppException("请先配置金华教育本地录取单位");
            }
//            // 调用金华接口判断是否已录取
//            EduJhjyQuerySyncVO eduJhjyQuerySyncVO = eduJhjyQuerySyncIntegration.queryJhjy(old);
//            if (StringUtils.isNotBlank(eduJhjyQuerySyncVO.getLqDw()) && !localDw.equals(eduJhjyQuerySyncVO.getLqDw())) {
//                throw new AppException("学生(" + old.getFullName() + ")已被" + eduJhjyQuerySyncVO.getLqDw() + "录取，请联系基教科处理");
//            }
//            if (StringUtils.isNotBlank(eduJhjyQuerySyncVO.getLqDw())) {
//                sendFlag = false;
//            }
            EduStudentEnrollVO queryVO = Convert.convert(EduStudentEnrollVO.class, old);
            EduDyjyQuerySyncVO eduDyjyQuerySyncVO = dyjyQuerySyncIntegration.querySyncInfo(queryVO);
            if (StringUtils.isNotBlank(eduDyjyQuerySyncVO.getLqDw()) && !localDw.equals(eduDyjyQuerySyncVO.getLqDw())) {
                throw new AppException("学生(" + old.getFullName() + ")已被" + eduDyjyQuerySyncVO.getLqDw() + "录取，请联系基教科处理");
            }
            if (StringUtils.isNotBlank(eduDyjyQuerySyncVO.getLqDw())) {
                sendFlag = false;
            }


            List<String> enrollStatusList = new ArrayList<>();
            enrollStatusList.add(EnrollStatusFormalEnum.dlq.getType());
            enrollStatusList.add(EnrollStatusFormalEnum.lq.getType());
            QueryWrapper<EduStudentEnroll> queryWrapper = new QueryWrapper<>();
            queryWrapper.lambda().select(EduStudentEnroll::getStudentEnrollId)
                    .eq(EduStudentEnroll::getParentId, old.getStudentEnrollId())
                    .in(EduStudentEnroll::getEnrollStatus, enrollStatusList)
                    .ne(EduStudentEnroll::getSchoolId, old.getSchoolId());
            if (eduStudentEnrollService.count(queryWrapper) > 0) {
                throw new AppException(old.getFullName() + "，东阳市其他学校待录取或者已录取");
            }
            List<String> enrollStatus1List = new ArrayList<>();
            enrollStatus1List.add(EnrollStatusFormalEnum.dsh.getType());
            enrollStatus1List.add(EnrollStatusFormalEnum.dlq.getType());
            QueryWrapper<EduStudentEnroll> otherQuery = new QueryWrapper<>();
            otherQuery.lambda().ne(EduStudentEnroll::getSchoolId, old.getSchoolId())
                    .eq(EduStudentEnroll::getIdcard, old.getIdcard())
                    .eq(EduStudentEnroll::getYear, old.getYear())
                    .in(EduStudentEnroll::getEnrollStatus, enrollStatus1List);
            List<EduStudentEnroll> otherList = eduStudentEnrollService.list(otherQuery);
            if (!CollectionUtils.isEmpty(otherList)) {
                for (EduStudentEnroll enroll : otherList) {
                    enroll.setEnrollStatus(EnrollStatusFormalEnum.xtblq.getType());
                    enroll.setAdmitFlag(BoolEnum.FALSE.getType());
                    enroll.setAdmitRemarks("因其他优先级高的学校录取，系统自动设置为不录取");
                    if (enroll.getAuthStatus().equals(AuthStatusEnum.NODO.getType())) {
                        enroll.setAuthStatus(AuthStatusEnum.NO.getType());
                        enroll.setAuthRemarks("因其他优先级高的学校录取，系统自动设置为审核不通过");
                        enroll.setAuthUserId(SessionUtil.getSessionInfo().getUserId());
                    }
                    enroll.setAdmitUserId(SessionUtil.getSessionInfo().getUserId());
                    eduStudentEnrollService.updateById(enroll);
                }
            }
            old.setEnrollStatus(EnrollStatusFormalEnum.lq.getType());
        } else {
            old.setEnrollStatus(EnrollStatusFormalEnum.ywblq.getType());
        }

        eduStudentEnrollService.updateById(old);
        return retVO;
    }


    }
